La section de spécification de langage Scala 6,19 dit:Scala pour compréhensions et carte partielle
A pour la compréhension
for (p <- e) yield e0
est traduit àe.map { case p => e0 }
Alors ...
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)
Jusqu'ici tout va bien:
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 ...
Pourquoi la deuxième version ne fonctionne-t-elle pas? Ou plutôt, pourquoi la première version fonctionne-t-elle?
en utilisant l.collect {case Left (x) => x} à la place. – Eastsun