背景
我正在嘗試使用帶有 ScalaEither型別的理解,即使用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 進行了一些更改,因此它變得偏右,但我看不出這些更改會如何影響此示例。
我錯過了什么?
uj5u.com熱心網友回復:
在 scala 2.11 中, Either 不是Monad。它缺少像 flatMap 和 map 這樣的組合器。相反,您呼叫.right或.left來獲得具有組合子的RightProjection或LeftProjection。您需要將您的Either投影為正確的。下面的代碼將回傳Right(6)。
for {
x <- Right(1).right
y <- Right(2).right
z <- Right(3).right
} yield x y z
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440185.html
