How to split a List[Either[A, B]]
Not sure this is really much neater, but :
scala> def splitEitherList[A,B](el: List[Either[A,B]]) = {
val (lefts, rights) = el.partition(_.isLeft)
(lefts.map(_.left.get), rights.map(_.right.get))
}
splitEitherList: [A, B](el: List[Either[A,B]])(List[A], List[B])
scala> val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))
el: List[Either[Int,String]] = List(Left(1), Right(Success), Left(42))
scala> val (leftValues, rightValues) = splitEitherList(el)
leftValues: List[Int] = List(1, 42)
rightValues: List[String] = List("Success")
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 don't even need a function that transforms our input into Right
or Left
to define the partitioning as we already have Right
s and Left
s. Thus a simple use of identity
:
val (lefts, rights) = List(Right(2), Left("a"), Left("b")).partitionMap(identity)
// lefts: List[String] = List(a, b)
// rights: List[Int] = List(2)
If scalaz
is one of your dependencies I would simply use separate
:
import scalaz.std.list._
import scalaz.std.either._
import scalaz.syntax.monadPlus._
val el : List[Either[Int, String]] = List(Left(1), Right("Success"), Left(42))
scala> val (lefts, rights) = el.separate
lefts: List[Int] = List(1, 42)
rights: List[String] = List(Success)