给一个Either[String,Int]
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)
^发布于 2015-04-01 17:06:47
if(a == 100) Left("foo") else Right(a)是一个Either[String, Int],而不是LeftProjection或RightProjection,所以它没有map或flatMap。你也需要投射它:
for {
a <- z.right
_ <- (if(a == 100) Left("foo") else Right(a)).right
} yield a这和一条线之间的区别是,一条线相当于:
for {
a <- z.right
} yield (if(a == 100) Left("foo") else Right(a))。。它在最后没有额外的map。
https://stackoverflow.com/questions/29396670
复制相似问题