scalaeither

Best way to turn a List of Eithers into an Either of a List?


I have some code like the below, where I have a List of Eithers, and I want to turn it into an Either of Lists. In particular (in this case), if there are any Lefts in the list, then I return a Left of the list of them, otherwise I return a Right of the list of the rights.

val maybe: List[Either[String, Int]] = getMaybe
val (strings, ints) = maybe.partition(_.isLeft)
strings.map(_.left.get) match {
  case Nil => Right(ints.map(_.right.get))
  case stringList => Left(stringList)
}

Calling get always makes me feel like I must be missing something.

Is there a more idiomatic way to do this?


Solution

  • data.partition(_.isLeft) match {                            
      case (Nil,  ints) => Right(for(Right(i) <- ints) yield i)        
      case (strings, _) => Left(for(Left(s) <- strings) yield s)
    }
    

    For one pass:

    data.partition(_.isLeft) match {                            
      case (Nil,  ints) => Right(for(Right(i) <- ints.view) yield i)        
      case (strings, _) => Left(for(Left(s) <- strings.view) yield s)
    }