强制Scala特性实现某种方法

ama*_*emi 4 scala traits mixins

有没有办法指定特征必须提供方法的具体实现?

鉴于一些mixin

class A extends B with C {
  foo()
}
Run Code Online (Sandbox Code Playgroud)

如果是,或者实现A,程序将编译.但是,我们怎么能强迫,例如,包含实施?BCfoo()Bfoo

gzm*_*zm0 10

您可以执行以下操作:

class A extends B with C {
  super[B].foo()
}
Run Code Online (Sandbox Code Playgroud)

这只会在B 实现时 编译foo.但请谨慎使用,因为它(可能)会引入一些不直观的耦合.此外,如果A覆盖foo,依然Bfoo将被调用.

一个IMHO有效用例是冲突解决:

trait B { def foo() = println("B") }
trait C { def foo() = println("C") }
class A extends B with C {
  override def foo() = super[B].foo()
}
Run Code Online (Sandbox Code Playgroud)

如果要确保B 声明 foo,可以使用类型归属:

class A extends B with C {
  (this:B).foo()
}
Run Code Online (Sandbox Code Playgroud)

这只会在B 声明时 编译foo(但可能在C或中实现A).