How to convert List[Either[String, Int]]
to Either[List[String], List[Int]]
using a method similar to cats sequence? For example, xs.sequence
in the following code
import cats.implicits._
val xs: List[Either[String, Int]] = List(Left("error1"), Left("error2"))
xs.sequence
returns Left(error1)
instead of required Left(List(error1, error2))
.
KevinWrights' answer suggests
val lefts = xs collect {case Left(x) => x }
def rights = xs collect {case Right(x) => x}
if(lefts.isEmpty) Right(rights) else Left(lefts)
which does return Left(List(error1, error2))
, however does cats provide out-of-the-box sequencing which would collect all the lefts?
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.
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