2
votes

If I have a List[Try[A]] in Scala, what is the idiomatic way to filter out the Failure(t) values?

One way is to use the following:

val someList: List[Try[String]] = ...
someList.filter(_.isFailure)

Is there a more "idiomatic" way, e.g. using flatten? This does seem pretty simple.

1

1 Answers

10
votes

If you want to get all exceptions you could use collect like this:

someList.collect{ case Failure(t) => t }
// List[Throwable]

If you want to get all success results you could use flatMap or collect:

someList.flatMap{ _.toOption }
// List[String]

someList.collect{ case Success(s) => s }