考虑一个代码:
val some: OneCaseClass Either TwoCaseClass = ???
val r = some.left.map(_.toString)
为什么是 rSerializable with Product with Either[String, TwoCaseClass]
类型而不是Either[String, TwoCaseClass]
?
如何仅映射左值?
因为那是的返回类型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)