Force Scala trait to implement a certain method

青春壹個敷衍的年華 提交于 2020-01-14 13:31:45

问题


Is there a way to specify that a trait has to provide a concrete implementation of a method?

Given some mixin

class A extends B with C {
  foo()
}

The program will compile if either of A, B, or C implements foo(). But how can we force, for example, B to contain foo's implementation?


回答1:


You can do the following:

class A extends B with C {
  super[B].foo()
}

This will only compile if B implements foo. Use with caution though as it (potentially) introduces some unintuitive coupling. Further, if A overrides foo, still B's foo will be called.

One IMHO valid use case is conflict resolution:

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

If you want to make sure B declares foo, you can use type ascription:

class A extends B with C {
  (this:B).foo()
}

This will only compile if B declares foo (but it might be implemented in C or A).



来源:https://stackoverflow.com/questions/17846085/force-scala-trait-to-implement-a-certain-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!