我可以在哪里找到
的信息trait After extends Context { outer => xxx
//...
}
outer => 是什么意思?
答案 0 :(得分:14)
这是一种自我类型。您还可以添加类型注释,以强制类,将您的特征扩展为特定类型。但是没有类型它只是对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