scala - `trait Y { this: X => }` 和 `trait Y extends X {}` 有什么区别

标签 scala traits

斯卡拉代码:

trait X

trait Y1 {
  this: X => 
}

trait Y2 extends X {
}

我想知道 Y1 和有什么区别和 Y2特质?如果我有一个类Z需要延长Y :
class Z1 extend Y1 with X

class Z2 extends Y2

这两个类似乎没有区别Z1Z2 .如果它们几乎相同,您会推荐哪种风格?

最佳答案

有时,您处于深度嵌套的作用域中,而别名对于外部对象很有用,例如 here .

如解释 here , this 的两种类型的线性化是颠倒的。

也就是说,你有 this: Y with Xthis: 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/

相关文章:

scala - 一键将一个大拼花文件拆分为多个拼花文件

rust - 在 Rust 中实现 Fn(&something) 的特征

rust - 在 Rust 中访问属性后调用 &mut self 上的方法

scala - Spark 计数大量列

java - 使用带有自定义 Bean 解析器的 .properties 文件

scala - Spark 无法计算表达式 : lag of a window expression

Scala,PureConfig - 如何读取 json 配置文件?

php - 特性与接口(interface)

class - 在 Scala 中,将对象方法组合为类方法

rust - 特征对象的 &mut 和 ref mut 之间的区别