Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How map only left value from scala Either?

Tags:

scala

either

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?

like image 276
Cherry Avatar asked Aug 27 '15 06:08

Cherry


1 Answers

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)
like image 139
dcastro Avatar answered Sep 28 '22 06:09

dcastro