Ben*_*itz 6 reflection scala traits path-dependent-type singleton-type
无论您是this.type从Trait内部还是从创建对象的范围引用,都会产生不同的结果.
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
println(Instance1.ttag =:= typeOf[Instance1.type]) // Should be true
Run Code Online (Sandbox Code Playgroud)
这是输出:
false // As expected: the singleton types of two objects are different.
Trait constructor: $line9.$read$$iw$$iw$$iw$$iw$Instance1$@58c46295
Trait constructor: $line10.$read$$iw$$iw$$iw$$iw$Instance2$@452451ba
true // But the this.type tags are equivalent
false // and the this.type tag is not equivalent to the singleton type.
Run Code Online (Sandbox Code Playgroud)
因此,有两个不同的对象,但显然每个对象都获得一个等效的类型标记this.type,这.type与从封闭范围看到的对象不同.
这是一个编译器错误,或者,如果没有,你能解释为什么这种行为有意义吗?
(我正在运行Scala 2.11.2.我尝试使用self别名this,结果相同.)
以下程序先打印 false,然后打印 true。在我看来,这两种情况之间应该没有实质性区别(尽管这实际上更多是一种意见;我真的不能说是否有理由):
import scala.reflect.runtime.universe._
object Test2 extends App {
def foo(): Type = {
object a
typeOf[a.type]
}
println(foo() =:= foo()) // false
trait Trait {
val ttag = typeOf[this.type]
}
object Instance1 extends Trait
object Instance2 extends Trait
println(Instance1.ttag =:= Instance2.ttag) // true
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |