Search code examples
scalafor-comprehension

Scala's either with tuple as Right


Suppose I have following code:

val either: Either[String, (Int, Int)] = Right((1,2))
for {
  (a, b) <- either.right
} yield a + b

When I evaluate it in REPL I get

:13: error: constructor cannot be instantiated to expected type; found : (T1, T2) required: scala.util.Either[Nothing,(Double, Double)] (a, b) <- a.right ^ :14: error: not found: value a } yield a + b ^

Why do I have such error? Can't I pattern match on tuple from Either's Right?


Solution

  • Issue seems to be a scala bug https://issues.scala-lang.org/browse/SI-7222. Converting the for comprehension to flatMap/map notation seems to work.

    val either: Either[String, (Int, Int)] = Right((1, 2))
    either.right.map {
      case (a, b) =>
        a + b
    }
    
    either: Either[String,(Int, Int)] = Right((1,2))
    res0: Serializable with Product with scala.util.Either[String,Int] = Right(3)