Created
April 11, 2017 00:44
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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