How map only left value from scala Either?

Cherry picture Cherry · Aug 27, 2015 · Viewed 10.9k times · Source

Consider a code:

val some: OneCaseClass Either TwoCaseClass = ???
val r = some.left.map(_.toString)

Why is r Serializable with Product with Either[String, TwoCaseClass] type instead of Either[String, TwoCaseClass]?

How to map only left value?

Answer

dcastro picture dcastro · Aug 27, 2015

Because that is the return type of LeftProjection.map.

map[X](f: (A) ⇒ X): Product with Serializable with Either[X, B]

But this is not a problem. You can use type ascription if you wish:

val r: Either[String, TwoCaseClass] = some.left.map(_.toString)

Take a look at the examples on the Either docs:

val l: Either[String, Int] = Left("flower")
val r: Either[String, Int] = Right(12)
l.left.map(_.size): Either[Int, Int] // Left(6)
r.left.map(_.size): Either[Int, Int] // Right(12)
l.right.map(_.toDouble): Either[String, Double] // Left("flower")
r.right.map(_.toDouble): Either[String, Double] // Right(12.0)