self 类型注释中 this 和 self 的区别? [英] Difference between this and self in self-type annotations?
问题描述
在各种 Scala 文献中,我看到一些使用this"和其他使用self"的自我类型注释:
In various Scala literature I see some self-type annotations using "this" and others using "self":
trait A { this: B => ... }
trait A { self: B => ... }
使用this"或self"之间有什么真正的区别吗?你用什么名字有关系吗?这同样有效吗?
Is there any real difference between using "this" or "self"? Does it matter at all what name you use? Is this just as valid?
trait A { foo: B => ... }
推荐答案
这三种形式都是有效的,并且具有 B
被假定为 this
的类型的效果在 A
类中.
All three forms are valid, and have the effect that B
is assumed as the type of this
in class A
.
前两个变体
trait A { self: B => ... }
trait A { foo: B => ... }
在特征A
中引入self
(分别为foo
)作为this
的别名.这对于从内部类访问 this
引用很有用.IE.然后,当从类访问特征 A
的 this
引用时,您可以使用 self
而不是 A.this
嵌套在其中.示例:
introduce self
(respectively, foo
) as an alias for this
in trait A
. This is useful for accessing the this
reference from an inner class. I.e. you could then use self
instead of A.this
when accessing the this
reference of the trait A
from a class nested within it. Example:
class MyFrame extends JFrame { frame =>
getContentPane().add( new JButton( "Hide" ) {
addActionListener( new ActionListener {
def actionPerformed( e: ActionEvent ) {
// this.setVisible( false ) --> shadowed by JButton!
frame.setVisible( false )
}
})
})
}
第三个变体,
trait A { this: B => ... }
不为this
引入别名;它只是设置 self 类型.
does not introduce an alias for this
; it just sets the self type.
这篇关于self 类型注释中 this 和 self 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!