Scala for concepts / loops and typed patterns

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.

+6
source share
1 answer

The translation obtained from the specification is actually

list.withFilter{case b: B => true; case _ => false}.foreach{case b: B => println(b)}

but it still compiles and works. Scala seems to be losing caseand translating into

list.withFilter{case b: B => true; case _ => false}.foreach{b: B => println(b)}

which will give the same error.

This turns out to be a known and old mistake: https://github.com/scala/bug/issues/900 .

Workaround subject to:

object Typed { def unapply[A](a: A) = Some(a) }

for { Typed(b: B) <- list } println(b)
+10
source

Source: https://habr.com/ru/post/1016708/


All Articles