Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created April 11, 2017 00:44
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fancellu/5b94deab0c676511dd7cd5ad26e88d21 to your computer and use it in GitHub Desktop.
Save fancellu/5b94deab0c676511dd7cd5ad26e88d21 to your computer and use it in GitHub Desktop.
A few ways to flatten down a Seq[Try] to only Success values
import scala.util.{Success, Failure}
val seq=Seq(Success(1), Failure(new Exception("bang")), Success(2))
// all emit List(1, 2)
seq.map(_.toOption).flatten
seq.flatMap(_.toOption)
seq.filter(_.isSuccess).map(_.get)
seq.collect{case Success(x) => x}
// if you wish to also handle failures, not just ignore
// emit List(1, 2)
// emit List(java.lang.Exception: bang)
val (successes, failures)=seq.partition(_.isSuccess)
successes.map(_.get)
failures.map(_.failed.get)
failures.collect{case Failure(ex) => ex}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment