我理解自我类型的结果是什么
trait SpellChecker {
self: RandomAccessSeq[char] =>
...
}来自http://www.markthomas.info/blog/92
但是我不明白为什么在这里使用self而不是this更好.!?另外,如果我编写asfd而不是self,我也不会得到编译器错误.所以我不太确定“自我”是什么意思。我看不出以后在这种特性的方法中像对象一样使用self是不可能的。
发布于 2016-10-09 20:35:52
self是SpellChecker实例的别名。如果您有嵌套结构(如类),这是非常有用的。考虑到这一点:
trait Foo {
self =>
override def toString : String = "Foo here"
class Bar {
def print() : Unit = {
println(s"this = $this")
println(s"self = $self")
}
override def toString : String = "Bar here"
}
}
val foo = new Foo {}
val bar = new foo.Bar()
bar.print()产出:
this = Bar here
self = Foo here因此,如果要引用外部元素,可以使用别名。使用this意味着没有别名,所以this : Example =>的意思是“我不需要这个别名,我只想确保它与示例混合在一起”。你可以给你的别名起名字,不管你喜欢什么,asfd和iLikeFries一样好。self只是某种约定。
发布于 2016-10-09 20:35:45
在这种情况下,重命名this是没有意义的。当您重命名外部this并在嵌套的模板/对象中访问它时,这在嵌套的情况下更有意义。
https://stackoverflow.com/questions/39948063
复制相似问题