老式特征扩展下的蛋糕方法有什么好处?
What are the benefits of the cake approach under old fashioned trait extending?
我试图找出通过 Cake 模式混合特征与通过老式扩展混合特征之间的区别。这是我的两个例子:
通过扩展
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() = ()
}
蛋糕法有什么好处?他们对我来说都是一样的。也许我错了,但我看不出任何显着差异。
如果我想丰富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()
}
"the cake approach" 相对于 "old fashion" 的主要优点是不预先设置层次结构约束 并通过使用 [=(最终)避免菱形问题=27=].
在您的示例中实现的构成 class U
的特征从右到左解析。拥有理智的方法解析顺序 (MRO) 使我们可以自由地在 "stackable fashion".
中混合任何特征
我试图找出通过 Cake 模式混合特征与通过老式扩展混合特征之间的区别。这是我的两个例子:
通过扩展
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() = ()
}
蛋糕法有什么好处?他们对我来说都是一样的。也许我错了,但我看不出任何显着差异。
如果我想丰富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()
}
"the cake approach" 相对于 "old fashion" 的主要优点是不预先设置层次结构约束 并通过使用 [=(最终)避免菱形问题=27=].
在您的示例中实现的构成 class U
的特征从右到左解析。拥有理智的方法解析顺序 (MRO) 使我们可以自由地在 "stackable fashion".