有没有办法指定特征必须提供方法的具体实现?
给定一些 mixin
class A extends B with C {
foo()
}
如果出现以下任一情况,程序将编译A
, B
, or C
实施foo()
。但是我们如何才能强制,例如,B
包含装有foo
的实施?
您可以执行以下操作:
class A extends B with C {
super[B].foo()
}
只有在以下情况下才会编译B
实施 foo
。但请谨慎使用,因为它(可能)会引入一些不直观的耦合。进一步地,如果A
覆盖foo
, still B
's foo
将被调用。
恕我直言,一个有效的用例是解决冲突 https://stackoverflow.com/questions/1836060/cant-extend-two-traits-that-have-a-method-with-the-same-signature:
trait B { def foo() = println("B") }
trait C { def foo() = println("C") }
class A extends B with C {
override def foo() = super[B].foo()
}
如果你想确定B
declares foo
,您可以使用类型归属:
class A extends B with C {
(this:B).foo()
}
只有在以下情况下才会编译B
declares foo
(但它可能会在C
or A
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)