According to section 6.19 of the Scala Language Specification, this is for a loop:
for (e <-p) e'
translates to:
p <- e.withFilter{case p => true; case _ => false}.foreach{case p => e′}
So why this little program:
object ForAndPatterns extends App {
class A()
class B() extends A
val list: List[A] = List(new A(), new B(), new B())
for {b: B <- list}
println(b)
}
gives this compilation error:
Error:(7, 13) type mismatch;
found : proves.ForAndPatterns.B => Unit
required: proves.ForAndPatterns.A => ?
for {b: B <- list}
when is this expression:
list.withFilter{case a: B => true; case _ => false}.foreach{case b => println(b)}
does not give errors.
source
share