I thought that inside a trait, this
referred to the object with the trait. But judging from the code below, sometimes it does and sometimes it doesn't.
import scala.reflect.runtime.universe._
trait Trait {
val ttag = typeOf[this.type]
println(s"Trait constructor: $this")
}
object Instance1 extends Trait
object Instance2 extends Trait
println(typeOf[Instance1.type] =:= typeOf[Instance2.type]) // Should be false
println(Instance1.ttag =:= Instance2.ttag) // Should be false
Here's the output:
Trait constructor: $line9.$read$$iw$$iw$$iw$$iw$Instance1$@58c46295
Trait constructor: $line10.$read$$iw$$iw$$iw$$iw$Instance2$@452451ba
false // As expected: the singleton types of two objects are different
true // But the this.type tags are equivalent!
So, there are two distinct objects, but apparently each is getting an equivalent type tag for its this.type
.
Is this a compiler bug, or, if not, could you explain why this behavior makes sense?
(I'm running Scala 2.11.2. I've tried it with a self
alias for this
, with the same result.)
Aucun commentaire:
Enregistrer un commentaire