强制Scala特性实施某种方法 [英] Force Scala trait to implement a certain method
问题描述
是否有一种方法可以指定特征必须提供方法的具体实现?
Is there a way to specify that a trait has to provide a concrete implementation of a method?
给出一些混入
class A extends B with C {
foo()
}
如果A
,B
或C
中的任何一个实现了foo()
,则程序将编译.但是,例如,如何强制B
包含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?
推荐答案
您可以执行以下操作:
class A extends B with C {
super[B].foo()
}
这仅在B
实现 foo
时编译.请谨慎使用,因为(可能)引入了一些不直观的耦合.此外,如果A
覆盖foo
,仍将调用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()
}
如果要确保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()
}
仅在B
声明 foo
时才编译(但是可以在C
或A
中实现).
This will only compile if B
declares foo
(but it might be implemented in C
or A
).
这篇关于强制Scala特性实施某种方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!