23

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?

micseydel
  • 381
  • 6
  • 13
Cherry
  • 31,309
  • 66
  • 224
  • 364

1 Answers1

26

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)
dcastro
  • 66,540
  • 21
  • 145
  • 155
  • 11
    It's worth noting that now (Scala 2.12) Either is right-biased. You don't have to explicitly do a right projection any more to map the value. So: r.map(_.toDouble) is equivalent to r.right.map(_.toDouble) – Guillaume Aug 14 '17 at 13:34