我试图提出一个组合场景,其中 self-type 和 extends 的行为不同,但到目前为止还没有找到。基本示例总是谈论不需要类/特征不必是依赖类型的子类型的自类型,但即使在这种情况下,自类型和扩展之间的行为似乎是相同的。
trait Fooable { def X: String }
trait Bar1 { self: Fooable =>
def Y = X + "-bar"
}
trait Bar2 extends Fooable {
def Y = X + "-bar"
}
trait Foo extends Fooable {
def X = "foo"
}
val b1 = new Bar1 with Foo
val b2 = new Bar2 with Foo
是否存在组合对象的某种形式的组合或功能在使用一种与另一种时有所不同的情况?
更新 1: 感谢提供没有自我打字就不可能的事情的例子,我很感激这些信息,但我真的在寻找可以自我和扩展但不能互换的组合。
更新 2: 我想我有一个特殊的问题是为什么各种 Cake Pattern 示例通常都在谈论必须使用 self-type 而不是 extends。我还没有找到一个与扩展不一样的蛋糕模式场景
最佳答案
循环引用可以用 self-types 来完成,但不能用 extends 来完成:
// Legal
trait A { self: B => }
trait B { self: A => }
// Illegal
trait C extends D
trait D extends C
当存在循环依赖时,我有时会使用它来拆分多个文件中的实现。
关于scala - 在什么情况下自类型注释提供扩展无法实现的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25413854/