斯卡拉代码:
trait X
trait Y1 {
this: X =>
}
trait Y2 extends X {
}
我想知道
Y1
和有什么区别和 Y2
特质?如果我有一个类Z
需要延长Y
:class Z1 extend Y1 with X
class Z2 extends Y2
这两个类似乎没有区别
Z1
和 Z2
.如果它们几乎相同,您会推荐哪种风格?
最佳答案
有时,您处于深度嵌套的作用域中,而别名对于外部对象很有用,例如 here .
如解释 here , this
的两种类型的线性化是颠倒的。
也就是说,你有 this: Y with X
和 this: X with Y
.this
事项(双关语):
scala> trait X { type T }
defined trait X
scala> trait Y { type T <: String ; def t: T ; def f = t.length }
defined trait Y
scala> trait Y { this: X => type T <: String ; def t: T ; def f = t.length }
<console>:8: error: value length is not a member of Y.this.T
trait Y { this: X => type T <: String ; def t: T ; def f = t.length }
^
scala> trait Y { this: X with Y => type T <: String ; def t: T ; def f = t.length }
defined trait Y
scala> trait Y extends X { type T <: String ; def t: T ; def f = t.length }
defined trait Y
但正如链接的权威答案所说,这可能永远无关紧要。
关于scala - `trait Y { this: X => }` 和 `trait Y extends X {}` 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439894/