首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Either.right =对和Either.Left=Left吗?

Either.right =对和Either.Left=Left吗?
EN

Stack Overflow用户
提问于 2020-02-12 17:29:05
回答 1查看 348关注 0票数 1

在下一个地点:

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

本报告介绍:

代码语言:javascript
复制
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
}

然而,我发现了一个错误:

代码语言:javascript
复制
[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

然而,当我用右替换Either.right和用左替换Either.left时,我得到了这样的代码编译:

代码语言:javascript
复制
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
}

所以,我想知道是什么让这一切发生的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-12 17:50:56

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

导入cats.syntax.either._才能使其工作。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60193998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档