可能重复:
“外部=>”的真正含义是什么?
我可以在哪里找到有关信息
trait After extends Context { outer => xxx
//...
}
外部 =>是什么意思?
这是一种自我类型。您还可以添加类型注释以强制将您的特征扩展为某种类型的类。但是没有类型它只是一个引用this
(并且被称为自引用),所以你可以在内部类等中使用它。例如:
class MyOuter { outer =>
// this == outer
class MyInner {
// this != outer
def creator = outer
}
}
例如,我提到的其他用法可用于向现有类添加特殊行为:
class MyClass {
val foo = "foo"
}
trait MyClassExtension { this: MyClass =>
def fooExtended(s: String) = foo + s
}
scala> val x = new MyClass with MyClassExtension
x: MyClass with MyClassExtension = $anon$1@5243618
scala> x.fooExtended("bar")
res3: java.lang.String = foobar
这里的this: MyClass =>
意思是,MyClassExtension
只能混入MyClass
.
scala> class OtherClass
defined class OtherClass
scala> val x = new OtherClass with MyClassExtension
<console>:11: error: illegal inheritance;
self-type OtherClass with MyClassExtension does not conform to MyClassExtension's selftype MyClassExtension with MyClass
val x = new OtherClass with MyClassExtension