給定一個Either[String,Int]
:轉換`flatMap`到`換comprehension`無論使用哪種
scala> val z: Either[String, Int] = Right(100)
z: Either[String,Int] = Right(100)
我可以寫與flatMap
下面的代碼:
scala> z.right.flatMap(x => if(x == 100) Left("foo") else Right(x))
res14: scala.util.Either[String,Int] = Left(foo)
但是,我在做什麼毛病for comprehension
版本?
scala> for {
| a <- z.right
| _ <- if(a == 100) Left("foo") else Right(a)
| } yield a
<console>:11: error: value map is not a member of Product with Serializable
with scala.util.Either[String,Int]
_ <- if(a == 100) Left("foo") else Right(a)
^