这样做的惯用scala方法是什么?我有一个列表,如果我找到符合某些条件的东西,则想要返回“Y”,否则返回“N”。我有一个“有效”的解决方案,但我不喜欢它......
def someMethod( someList: List[Something]) : String = {
someList.foreach( a =>
if (a.blah.equals("W") || a.bar.equals("Y") ) {
return "Y"
}
)
"N"
}
答案 0 :(得分:11)
Simples:
if (someList.exists{ a=> a.blah == "W" || a.bar == "Y"})
"Y"
else
"N"
答案 1 :(得分:8)
def condition(i: Something) = i.blah.equals("W") || i.bar.equals("Y")
somelist.find(condition(_)).map(ignore => "Y").getOrElse("N")
或只是
if (somelist exists condition) "Y" else "N"
答案 2 :(得分:2)
假设Something有一个blah成员。
def someMethod(someList: List[Something]): String =
if (someList forall { a => a.blah == "W" || a.blah == "Y" }) "Y" else "N"
答案 3 :(得分:1)
val l = List(1,2,3,4)
(l.find(x => x == 0 || x == 1)) match { case Some(x) => "Y"; case _ => "N"}
res: java.lang.String = Y
答案 4 :(得分:0)
假设Something
可以匹配模式,例如当它像一个案例类......
case class Something(blah:String, bar:String)
......你可以写......
def someMethod(someList: List[Something]) = someList.collect{
case Something("W",_) | Something(_,"Y") => "Y"}.headOption.getOrElse("N")