与“this"没有类型/差异的显式自引用 [英] Explicit self-references with no type / difference with ''this''
问题描述
我了解明确输入的自引用的用法:
trait T {
self : T2 =>
...
}
在正文中,self
是this
的别名,但具有更精确的类型T with T2
.
In the body, self
is an alias for this
but has the more precise type T with T2
.
现在,我已经在代码中看到了这一点:
Now, I've seen this in code:
trait T {
self =>
...
}
也就是说,一个没有附加类型信息的显式自引用.在这种配置中,是否存在 self
不仅仅是 this
的别名的情况?
That is, an explicit self reference with no additional type information. In this configuration, is there any situation in which self
is not just an alias for this
?
推荐答案
它是 this
的别名.
您的第一个示例有助于确保将特征混合到适当的类型中,并使这些方法可用.
Your first example is useful for ensuring that the trait has been mixed in to an appropriate type, and makes those methods available.
当您的内部类具有命名冲突时,第二个示例非常有用,可以使外部作用域可见.例如:
The second example is useful when you have inner classes with naming conflicts, to make the outer scope visible. For example:
trait U {
self =>
val name = "outer"
val b = new AnyRef {
val name = "inner"
println(name)
println(this.name)
println(self.name)
}
}
然后new AnyRef with U
打印
inner
inner
outer
self"不是一个特殊的关键字——你可以使用bananas =>"或任何你喜欢的东西,但它经常被惯例使用.
"self" is not a special keyword - you can use "bananas =>" or whatever you like, but it's often used by convention.
这在 Swing 中经常出现,你在内部类(滚动窗格中的文本框等)上做了很多,通常有许多与外部类同名的方法.
This crops up quite a bit in Swing, where you make a lot on inner classes (textboxes within scrollpanes, etc), which usually have many methods with the same names as the outer classes.
这篇关于与“this"没有类型/差异的显式自引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!