0

I get one error when I use for comprehensions with if guard in this way.

code:

for {
  foo <- Left[String,String]("teststring").right
  bar <- Right[String,String]("teststring").right if (foo==bar)
} yield (bar)

error:

error: type mismatch;
 found   : Option[scala.util.Either[Nothing,String]]
 required: scala.util.Either[?,?]
                bar <- Right[String,String]("teststring").right if (foo==bar)
                    ^
angelokh
  • 9,394
  • 6
  • 61
  • 119

2 Answers2

0

This is what I did to fix above error. I also move if-guard to later process.

val result = for {
  foo <- Right[String,String]("teststring").right
  bar <- Right[String,String]("teststring").right
} yield (foo, bar)

result fold (
  ex => Left("Operation failed with " + ex),
  v => v match { 
    case (x,y) =>
        if (x == y) Right(x)
        else Left("value is different")
  } 
)
angelokh
  • 9,394
  • 6
  • 61
  • 119
0

You can't do what you're trying to do since the types of all statements in a for-comprehension need to be of the same type, and the if (foo == bar) filter expression makes the last expression an Option[Either[?,?]] instead of Either[?,?].

One way to get around this is to desugar the expression into a series of flatMap, map and filter expressions.

Another way is to lose the the Left of either, and just use the toOption method on the RightProjection, i.e.:

for {
  foo <- Left[String,String]("left").right.toOption
  bar <- Right[String,String]("right").right.toOption if (foo == bar)
} yield (foo)
Community
  • 1
  • 1
yan
  • 19,660
  • 3
  • 33
  • 47