scala - Converting `flatMap` to `for-comprehension` with Either -
given either[string,int]:
scala> val z: either[string, int] = right(100) z: either[string,int] = right(100)   i can write following code flatmap:
scala> z.right.flatmap(x => if(x == 100) left("foo") else right(x)) res14: scala.util.either[string,int] = left(foo)   but, doing wrong for comprehension version?
scala> {      |  <- z.right      |  _ <- if(a == 100) left("foo") else right(a)      | } yield <console>:11: error: value map not member of product serializable           scala.util.either[string,int]                _ <- if(a == 100) left("foo") else right(a)                     ^      
if(a == 100) left("foo") else right(a) either[string, int], , not leftprojection or rightprojection, doesn't have map or flatmap. need project well:
for {     <- z.right     _ <- (if(a == 100) left("foo") else right(a)).right } yield   the difference between , one-liner one-liner equivalent to:
for {     <- z.right } yield (if(a == 100) left("foo") else right(a))   .. not have map @ end.
Comments
Post a Comment