Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 472
pathikrit Avatar asked Nov 06 '14 21:11

pathikrit


2 Answers

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

inputs.iterator.map(foo).collectFirst { case Success(x) => x }
like image 181
Michael Zajac Avatar answered Sep 28 '22 18:09

Michael Zajac


You want this:

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

It returns an Option[B].

like image 22
Nate Avatar answered Sep 28 '22 17:09

Nate