Search code examples
scalaeither

why can't I extract a tuple from Either projection inside for comprehension using pattern matching?


Why does this work:

val somePair: Option[(String,String)] = Some(("John", "Doe"))
(for {
  pair <- somePair.toRight("Hello unknown!").right
} yield s"Hello ${pair._1} ${pair._2}!").merge

But this doesn't:

val somePair: Option[(String,String)] = Some(("John", "Doe"))
(for {
  (name,lastName) <- somePair.toRight("Hello unknown!").right
} yield s"Hello $name $lastName!").merge

Edit:
I should add this is the error message:
Error:(43, 4) constructor cannot be instantiated to expected type; found : (T1, T2) required: scala.util.Either[Nothing,(String, String)] (name,lastName) <- somePair.toRight("Hello unknown!").right ^


Solution

  • This is a bug in Scala which is unfortunately open since quite some time.

    Take a look at https://issues.scala-lang.org/browse/SI-5589 for reference.