Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

partition of a List[Try[String]] in Scala

Tags:

scala

I have a List of Trys, and I need to partition by Failures and Successes, 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
like image 305
David Portabella Avatar asked Jan 06 '23 05:01

David Portabella


1 Answers

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 Successes as Rights and Failures as Lefts:

// 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)
like image 152
Xavier Guihot Avatar answered Jan 07 '23 18:01

Xavier Guihot