The Scala language specification section 6.19 says:
A for comprehension
for (p <- e) yield e0is translated toe.map { case p => e0 }
So…
scala> val l : List[Either[String, Int]] = List(Left("Bad"), Right(1))
l: List[Either[String,Int]] = List(Left(Bad), Right(1))
scala> for (Left(x) <- l) yield x
res5: List[String] = List(Bad)
So far so good:
scala> l.map { case Left(x) => x }
<console>:13: warning: match is not exhaustive!
missing combination Right
l.map { case Left(x) => x }
^
scala.MatchError: Right(1)
at $anonfun$1.apply(<console>:13)
at ...
Why does the second version not work? Or rather, why does the first version work?
If you use pattern matching in your
for-comprehension the compiler will actually insert a call tofilterwith aninstanceOf-check before applying themap.EDIT:
Also in section 6.19 it says:
A generator is defined earlier on as:
When inspecting the bytecode you will see the call to
filterpreceding the call tomap.