我试图找出通过蛋糕模式混合特征和通过老式延伸混合它们之间的区别。以下是我的两个例子:
通过扩展
trait X {
def foo()
}
trait Y extends X {
def bar()
}
class Z extends Y {
def foo() = ()
def bar() = ()
}
并通过Cake
trait N {
def foo()
}
trait M {
this: N =>
def bar()
}
class U extends M with N {
def bar() = ()
def foo() = ()
}
蛋糕方法有什么好处?它们对我来说都是一样的。也许我错了,但我看不出任何重大差异。
答案 0 :(得分:1)
如果我想丰富X
的功能,第一种方法:
// I am X
// I give you everything X provides
trait Y extends X {
def bar()
}
如果我想使用N
的功能,我会使用第二种方法:
// I am an extension of N
// I require you to be N
trait M { this: N =>
def bar()
}
“蛋糕方法”相对于“旧时尚”的主要好处不是通过使用“特征线性化”来设置层次约束 upfront 并避免(最终)钻石问题。
在您的示例中实现的class U
形成的特征从右到左得到解决。拥有理智的方法解决令(MRO)让我们可以自由地以“可堆叠的方式”混合任何特征。