正确的做法是不使用 Scala 进行理解
背景
我试图将 Scala 的推导式与 Either
类型一起使用,即使用 Right
。 然而,尽管我付出了努力,我还是收到错误并且没有任何效果。
代码
我正在使用 scala 的 repl 进行一些测试。这是我能想到的最简单的用例:
scala> for {
| x <- Right(1)
| y <- Right(2)
| z <- Right(3)
| } yield x + y + z
您将看到它基本上是此页面的副本:
https://www.scala-lang.org/api/2.12.7/scala/util/Either.html
问题
但是,此操作失败并出现以下错误:
<console>:13: error: value flatMap is not a member of scala.util.Right[Nothing,Int]
x <- Right(1)
^
<console>:14: error: value flatMap is not a member of scala.util.Right[Nothing,Int]
y <- Right(2)
^
<console>:15: error: value map is not a member of scala.util.Right[Nothing,Int]
z <- Right(3)
^
我正在使用以下版本scala 的:
Welcome to Scala 2.11.12 (OpenJDK 64-Bit Server VM, Java 11.0.13).
Type in expressions for evaluation. Or try :help.
我知道对 Either 进行了一些更改,因此它变得右偏,但我不知道这些更改会如何影响此示例。
我缺少什么?
Background
I am trying to use comprehensions with Scala with the Either
type, namely using a Right
.
However, despite my efforts, I get an error and nothing works.
Code
I am using scala's repl to make a few tests. This is the easiest use case I could come up with:
scala> for {
| x <- Right(1)
| y <- Right(2)
| z <- Right(3)
| } yield x + y + z
You will see it is basically a copy of this page:
https://www.scala-lang.org/api/2.12.7/scala/util/Either.html
Problem
However, this fails with the following error:
<console>:13: error: value flatMap is not a member of scala.util.Right[Nothing,Int]
x <- Right(1)
^
<console>:14: error: value flatMap is not a member of scala.util.Right[Nothing,Int]
y <- Right(2)
^
<console>:15: error: value map is not a member of scala.util.Right[Nothing,Int]
z <- Right(3)
^
I am using using the following version of scala:
Welcome to Scala 2.11.12 (OpenJDK 64-Bit Server VM, Java 11.0.13).
Type in expressions for evaluation. Or try :help.
I understand some changes were made to Either, so it became Right biased, but I don't see how such changes could affect this example.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 scala 2.11 中,Either 不是 Monad。其中缺少诸如 flatMap 和 map 之类的组合器。相反,您可以调用 .right 或 .left 来获取确实具有组合器的 RightProjection 或 LeftProjection。您需要正确地预测您的任一。下面的代码将返回Right(6)。
In scala 2.11 Either is not a Monad. Combinators like flatMap and map are missing from it. Instead, you call .right or .left to get a RightProjection or LeftProjection which does have the combinators. You need to project your Either as right. The code below will return Right(6).