scala - 是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
}
所以,我想知道是什么导致了这种情况发生。
解决方案
这是猫对标准Either
对象的扩展。
导入cats.syntax.either._
以使其正常工作。
推荐阅读
- swift - 不受支持的架构 - Metal 和 Swift 之间的共享枚举
- java - 无法为 org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler 类型的对象设置未知属性“nav_version”
- laravel - 带模型和变量的路由
- c - 控件不流过第 45 行
- angular - ReferenceError:未定义 HTMLVideoElement
- sql - 如何更改具有 3600 万行的临时表以添加新列?
- ibm-cloud - 语音识别、批处理、语音分析、404【无此类子资源】
- reactjs - 做出反应。如何在组件树中调用特定子子项的方法
- php - 如何在 Codeigniter 4 中为所有页面设置特定语言
- opencv - 使用 opencv 查找直观的图像方向