Scala: try until the first success on the list

What is the idiomatic way of applying the function A => Try[B] to List[A] and returns either the first successful result of Some[B] (it is short-circuited), or if all else 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 } 
+6
source share
2 answers

You can do the same using collectFirst in one step:

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

Do you want to:

 inputs .iterator // or view (anything lazy works) .map(foo) .find(_.isSuccess) .map(_.get) 

It returns Option[B] .

+5
source

Source: https://habr.com/ru/post/977852/


All Articles