Is there a simple way to flatten a collection of try\'s to give either a success of the try values, or just the failure? For example:
def map(l:List[Int]) =
Starting in Scala 2.13
, most collections are provided with a partitionMap method which partitions elements based on a function returning either Right
or Left
.
In our case we can call partitionMap
with a function that transforms our Try
s into Either
s (Try::toEither) in order to partition Success
es as Right
s and Failure
s as Left
s.
Then it's just a matter of matching the resulting partitioned tuple of lefts and rights based on whether or not there are lefts:
tries.partitionMap(_.toEither) match {
case (Nil, rights) => Success(rights)
case (firstLeft :: _, _) => Failure(firstLeft)
}
// * val tries = List(Success(10), Success(20), Success(30))
// => Try[List[Int]] = Success(List(10, 20, 30))
// * val tries = List(Success(10), Success(20), Failure(new Exception("error1")))
// => Try[List[Int]] = Failure(java.lang.Exception: error1)
Details of the intermediate partitionMap
step:
List(Success(10), Success(20), Failure(new Exception("error1"))).partitionMap(_.toEither)
// => (List[Throwable], List[Int]) = (List(java.lang.Exception: error1), List(10, 20))