17

考虑一个代码:

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

为什么是 rSerializable with Product with Either[String, TwoCaseClass]类型而不是Either[String, TwoCaseClass]

如何仅映射左值?

4

1 回答 1

22

因为那的返回类型LeftProjection.map

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

但这不是问题。如果您愿意,可以使用类型归属:

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

查看Either文档中的示例:

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)
于 2015-08-27T07:37:03.310 回答