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?
CodePudding user response:
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).
for {
x <- Right(1).right
y <- Right(2).right
z <- Right(3).right
} yield x y z