I have a List
of Try
s, and I need to partition by Failure
s and Success
es, as follows:
import scala.util.{Try, Success, Failure}
val list = List(Success(10), Success(20), Failure(new Exception("error1")), Success(30))
val (listTryFailures: List[Try[Int]], listTrySuccesses: List[Try[Int]]) = list.partition(_.isFailure)
listTryFailures: List[Try[Int]] = List(Failure(java.lang.Exception: error1))
listTrySuccesses: List[Try[Int]] = List(Success(10), Success(20), Success(30))
val (listFailures: List[Throwable], listSuccesses: List[Int]) = (listTryFailures.map(_.failed.get), listTrySuccesses.map(_.get))
listFailures: List[Throwable] = List(java.lang.Exception: error1)
listSuccesses: List[Int] = List(10, 20, 30)
Is there already a function to achieve this?
(instead of calling the ugly partition(_.isFailure)
+ map(_.failed.get)
+ map(_.get)
)?
ps: Another option is as follows:
val listFailures: List[Throwable] = list.collect { case Failure(f) => f }
val listSuccesses: List[String] = list.collect { case Success(entry) => entry }
// or
val listFailures: List[Throwable] = list.flatMap(_.failed.toOption)
val listSuccesses: List[String] = list.flatMap(_.toOption)
but I am asking if a partitionSuccess
(or similar name) function already exists in a standard library:
val (listFailures: List[Throwable], listSuccesses: List[Int]) = list.partitionSuccess
Starting Scala 2.13
, most collections are now provided with a partitionMap
method which partitions elements based on a function which returns either Right
or Left
.
In our case we can call partitionMap
with a function that transforms our Try
into Either
in order to partition Success
es as Right
s and Failure
s as Left
s:
// val list = List(Success(10), Success(20), Failure(new Exception("error1")))
val (failures, successes) = list.partitionMap(_.toEither)
// failures: List[Throwable] = List(java.lang.Exception: error1)
// successes: List[Int] = List(10, 20)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With