【发布时间】:2021-10-01 05:53:57
【问题描述】:
问题是,当实现两个已知特征时,是否有任何方法(不涉及反射黑魔法)隐式覆盖方法?
假设我们有一个类SysImpl 实现了两个mixin:System 和Container:
// Where system acts as the interface for another consumer
trait System {
def isEmpty = false
}
trait Container[A] {
val elements = mutable.Set[A]()
}
// Then, we typically implement:
class SysImpl extends System with Container[Int] {
// We override the default system implementation here
override def isEmpty = elements.isEmpty
}
仅作为示例。
是否有任何方法可以实现第三个特征,或者对原始特征进行一些修改,从而使实现隐式覆盖isEmpty 方法,以防System 和Container[A] 存在?
我首先想到的是创建一个扩展方法,但这将是最好的阴影(不是吗?)。我需要正确覆盖该方法,因为调用是由只看到Systems 的消费者分派的。
(示例,省略细节)
class AImpl extends System with Container[A]
object Consumer {
def consume(sys: System) = if (sys.isEmpty) { /* Do things */ }
}
// Somewhere...
object Main {
def main() = {
Consumer.consume(new AImpl)
}
}
【问题讨论】:
-
为什么
Container不实现isEmpty? -
好吧,我在这里使用了
isEmpty这个词,但在我的实现中更像是isUnused,也是System的消费者,他需要知道System已准备好停用。而消费者不知道Container[A] -
为什么不直接引入第三个特征来扩展这两个特征,并覆盖
isEmpty,而不是扩展这两个SysImpl,而只是扩展这个新特征? -
@LuisMiguelMejíaSuárez 这确实是一种解决方案
标签: scala overriding traits mixins implicit