斯卡拉:在名单上尝试第一次成功

pat*_*rit 7 functional-programming scala try-catch fold scalaz

什么是在a A => Try[B]上应用函数List[A]并返回第一个成功结果Some[B](它短路)或者如果一切都失败,返回的惯用方法None

我想做这样的事情:

val inputs: List[String] = _

def foo[A, B](input: A): Try[B] = _

def main = {
  for {
   input <- inputs 
  } foo(input) match {
    case Failure(_) => // continue
    case Success(x) => return Some(x) //return the first success
  }
  return None   // everything failed
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*jac 10

你可以用collectFirst一个较少的步骤来做同样的事情:

inputs.iterator.map(foo).collectFirst { case Success(x) => x }
Run Code Online (Sandbox Code Playgroud)


Nat*_*ate 6

你要这个:

inputs
  .iterator // or view (anything lazy works)
  .map(foo)
  .find(_.isSuccess)
  .map(_.get)
Run Code Online (Sandbox Code Playgroud)

它返回一个Option[B].