如何只从scala中映射左值?

Che*_*rry 11 scala either

考虑一下代码:

val some: OneCaseClass Either TwoCaseClass = ???
val r = some.left.map(_.toString)
Run Code Online (Sandbox Code Playgroud)

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

如何只映射左值?

dca*_*tro 15

因为那返回类型LeftProjection.map.

map[X](f: (A) ? X): Product with Serializable with Either[X, B]
Run Code Online (Sandbox Code Playgroud)

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

val r: Either[String, TwoCaseClass] = some.left.map(_.toString)
Run Code Online (Sandbox Code Playgroud)

看看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)
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,现在(Scala 2.12)要么是偏右的.您不必再显示正确的投影来映射值.所以:r.map(_.toDouble)相当于r.right.map(_.toDouble) (3认同)