您可以同时拥有自类型和this
别名:
abstract class Parser[+T] { p: SomeAssumedType => … }
如果你不包含类型归属,Scala 将假定变量的类型是周围类的类型,从而给你一个简单的this
.
如果您保留名称this
和归属,那么 Scala 期望您以可以满足归属的方式初始化这个类。
至于this
混叠。这是需要这样做的情况:
object OuterObject { outer =>
val member = "outer"
object InnerObject {
val member = "inner"
val ref1 = member
val ref2 = this.member
val ref3 = outer.member
def method1 = {
val member = "method"
member
}
def method2 = {
val member = "method"
this.member
}
def method3 = {
val member = "method"
outer.member
}
}
}
scala> OuterObject.InnerObject.ref1
res1: java.lang.String = inner
scala> OuterObject.InnerObject.ref2
res2: java.lang.String = inner
scala> OuterObject.InnerObject.ref3
res3: java.lang.String = outer
scala> OuterObject.InnerObject.method1
res4: java.lang.String = method
scala> OuterObject.InnerObject.method2
res5: java.lang.String = inner
scala> OuterObject.InnerObject.method3
res6: java.lang.String = outer