【问题标题】:How map only left value from scala Either?如何仅从 scala Either 映射左值?
【发布时间】:2015-08-27 06:27:45
【问题描述】:

考虑一个代码:

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

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

如何只映射左值?

【问题讨论】:

    标签: scala either


    【解决方案1】:

    因为LeftProjection.map的返回类型。

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

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

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

    看看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)
    

    【讨论】:

    • 值得注意的是,现在 (Scala 2.12) 无论是右偏。您不必再显式地进行正确的投影来映射该值。所以:r.map(.toDouble) 等价于 r.right.map(.toDouble)
    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多