Convert List[Either[A, B]] to Either[List[A], List[B]]

Another variation on the same theme (similar to this answer), all imports included:

import scala.util.Either
import cats.data.Validated
import cats.syntax.traverse._
import cats.instances.list._

def collectErrors[A, B](xs: List[Either[A, B]]): Either[List[A], List[B]] = {
  xs.traverse(x => Validated.fromEither(x.left.map(List(_)))).toEither
}

If you additionally import cats.syntax.either._, then the toValidated becomes available, so you can also write:

xs.traverse(_.left.map(List(_)).toValidated).toEither

and if you additionally replace the left.map by bimap(..., identity), you end up with @DmytroMitin's wonderfully concise solution.


This solution doesn't use cats, but from Scala 2.13, you can use of partitionMap:

    def convert[L,R](input: List[Either[L,R]]): Either[List[L], List[R]] = {
      val (left, right) = input.partitionMap(identity)
      if (left.isEmpty) Right(right) else Left(left)
    }

    println(convert(List(Left("error1"), Left("error2"))))
    // Left(List(error1, error2))
    println(convert(List(Right(1), Left("2"), Right(3), Left("4"))))
    // Left(List(2, 4))
    println(convert(List(Right(1), Right(2), Right(3), Right(4))))
    // Right(List(1, 2, 3, 4))

Try

xs.traverse(_.toValidated.bimap(List(_), identity)).toEither

// List(Left("error1"), Left("error2")) => Left(List("error1", "error2"))
// List(Right(10), Right(20))           => Right(List(10, 20))
// List(Right(10), Left("error2"))      => Left(List("error2"))