我不确定这是你的意思,但这是我的尝试:
object CondSO extends App {
def condition(site: String): Boolean = site.contains("flow")
def complexCalc(db: List[String]) = db.filter(condition)
// abc is not a variable (as addressed in original Q), but rather a method
def abc(db: List[String]): Option[String] =
// orig. Q was a bit confusing what result is - boolean or something else?
// so, here it's returning a list of results
complexCalc(db).headOption
// second version - the "for" approach
def abc2(db: List[String]): Option[String] = (
for (site <- db if condition(site)) yield site
).headOption
// third version - using return
// probably fastest option. IMO other options could be
// similarly fast if they would be rewritten to use stream
// (they construct auxiliary list with all matching sites, not only first one)
def abc3(db: List[String]): Option[String] = {
for (site <- db if condition(site)) return Some(site)
None
}
// last version - custom foreach
implicit class IterablePimps[A](val i: Iterable[A]) {
def foreachWithReturn[B](f: A => Option[B]): Option[B] = {
while (i.iterator.hasNext)
f(i.iterator.next()) match {
case a: Some[B] => return a
case _ =>
}
None
}
}
def abc4(db: List[String]): Option[String] =
db.foreachWithReturn(s => if (condition(s)) Some(s) else None)
// testing section
val dbs = Map[String, List[String]](
"empty " -> List(),
"present" -> List("google.com", "stackoverflow.com"),
"absent " -> List("root.cz", "abclinuxu.cz")
)
val funcs = Map[String, (List[String]) => Option[String]](
"filter" -> abc,
"for " -> abc2,
"return" -> abc3,
"pimp " -> abc4
)
for {
db <- dbs
f <- funcs
} println(s"Applying ${f._1} on list ${db._1}: ${f._2(db._2)}")
}
输出:
Applying filter on list empty : None
Applying for on list empty : None
Applying return on list empty : None
Applying pimp on list empty : None
Applying filter on list present: Some(stackoverflow.com)
Applying for on list present: Some(stackoverflow.com)
Applying return on list present: Some(stackoverflow.com)
Applying pimp on list present: Some(stackoverflow.com)
Applying filter on list absent : None
Applying for on list absent : None
Applying return on list absent : None
Applying pimp on list absent : None
编辑:修改方法以返回一个结果,而不是选项中的列表。添加了更多可能的解决方案(基于新信息 frmo 提问者)