scalafunctional-programmingtry-catchscalazfold

Scala: Try till first success on a list


What is the idiomatic way of applying a function A => Try[B] on a List[A] and return either the first succesful result Some[B] (it short-circuits) or if everything fails, returns None

I want to do something like this:

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
}

Solution

  • You can do the same thing using collectFirst in one less step:

    inputs.iterator.map(foo).collectFirst { case Success(x) => x }