Search code examples
scalaeither

How to split a List[Either[A, B]]


I want to split a List[Either[A, B]] in two lists.

Is there a better way ?

def lefts[A, B](eithers : List[Either[A, B]]) : List[A] = eithers.collect { case Left(l) => l}
def rights[A, B](eithers : List[Either[A, B]]) : List[B] = eithers.collect { case Right(r) => r}

Solution

  • 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")