Scala 语言规范第6.19节说:
A for comprehension
for (p <- e) yield e0
被翻译为e.map { case p => e0 }
所以...
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)
到现在为止还挺好:
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 ...
为什么第二个版本不行?或者更确切地说,为什么第一个版本有效?