首页 > 解决方案 > 是Either.right = Right 和Either.Left=Left?

问题描述

在下一个站点:

https://typelevel.org/cats/datatypes/either.html

介绍:

object EitherStyle {
  def parse(s: String): Either[Exception, Int] =
    if (s.matches("-?[0-9]+")) Either.right(s.toInt)
    else Either.left(new NumberFormatException(s"${s} is not a valid integer."))

  def reciprocal(i: Int): Either[Exception, Double] =
    if (i == 0) Either.left(new IllegalArgumentException("Cannot take reciprocal of 0."))
    else Either.right(1.0 / i)

  def stringify(d: Double): String = d.toString
}

然而,我得到了错误:

[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:16:39: value right is not a member of object scala.util.Either
[error]     if (s.matches("-?[0-9]+")) Either.right(s.toInt)
[error]                                       ^
[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:17:17: value left is not a member of object scala.util.Either
[error]     else Either.left(new NumberFormatException(s"${s} is not a valid integer."))
[error]                 ^
[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:21:14: value left is not a member of object scala.util.Either
[error]       Either.left(new IllegalArgumentException("Cannot take reciprocal of 0."))
[error]              ^
[error] /application/learningSBT/hello-world/src/main/scala/Main.scala:22:17: value right is not a member of object scala.util.Either
[error]     else Either.right(1.0 / i)
[error]                 ^
[error] four errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 2 s, completed Feb 12, 2020 10:25:02 AM

但是,当我用 Right 替换 Either.right 和用 Left 替换 Either.left 时,我得到了以下代码编译:

object EitherStyle {
  def parse(s: String): Either[Exception, Int] =
    if (s.matches("-?[0-9]+")) Right(s.toInt)
    else Left(new NumberFormatException(s"${s} is not a valid integer."))

  def reciprocal(i: Int): Either[Exception, Double] =
    if (i == 0)
      Left(new IllegalArgumentException("Cannot take reciprocal of 0."))
    else Right(1.0 / i)

  def stringify(d: Double): String = d.toString
}

所以,我想知道是什么导致了这种情况发生。

标签: scalascala-cats

解决方案


这是猫对标准Either对象的扩展。

导入cats.syntax.either._以使其正常工作。


推荐阅读