Search code examples
scalaseqeither

Project a sequence of 'Left's from a sequence of Eithers?


(Caveat - I'm a scala noob) Given a sequence of Eithers, viz

theResults : Seq[Either[Error, String]]

I am trying to extract all the Errors by using a map on the left(s)

theResults match {
  case r if r.exists(_.isLeft)  => {
    val errors = theResults.map(r => r.left)
    ...
  }

However, this returns

Seq[Either.LeftProjection[ErrorResponse, String]]

Instead of the Seq[ErrorResponse] as I was hoping for.

Please put me out of my misery?


Solution

  • The easiest option would probably be:

    val lefts = theResults.map(_.left.toOption).flatten
    

    which will return a sequence of Error (or whatever the left type is).

    Personally, I think that scalaz Either is nicer to work with, as it's right-biased...