Why is this Scala translation for loop not equivalent?
I tried to write this code
val req: mutable.Buffer[InterfaceHttpData] = /*...*/
for (attr: Attribute <- req) {
println(attr.getValue())
}
This gives me the following error:
type mismatch;
found : io.netty.handler.codec.http.multipart.Attribute => Unit
required: io.netty.handler.codec.http.multipart.InterfaceHttpData => ?
I've read the specs and as far as I can tell this loop should be equivalent to the following.
req.withFilter { case attr: Attribute => true; case _ => false }.foreach {
case attr: Attribute => println(attr.getValue())
}
This compiles cleanly. I don't understand how the loop conversion is done?
+3
source to share
1 answer
According to the spec, this conversion only applies if p
in is p <- e
irrefutable for the type e
, which in your example means (p: U) <- (e: F[T])
where T <: U
.
scala> trait T
defined trait T
scala> class C extends T
defined class C
scala> val c: List[C] = Nil
c: List[C] = List()
scala> for (e: T <- c) println(e)
scala> val t: List[T] = Nil
t: List[T] = List()
scala> for (e: C <- t) println(e)
<console>:14: error: type mismatch;
found : C => Unit
required: T => ?
for (e: C <- l) println(e)
^
0
source to share