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
}
You can do the same thing using collectFirst
in one less step:
inputs.iterator.map(foo).collectFirst { case Success(x) => x }
You want this:
inputs
.iterator // or view (anything lazy works)
.map(foo)
.find(_.isSuccess)
.map(_.get)
It returns an Option[B]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With