问题是,当实现两个已知特征时,是否有任何方法(不涉及反射黑魔法)隐式重写方法?
认为我们有一个类SysImpl
,它实现了两个mixins: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
和 容器[A]
存在吗?
我想到的第一件事是创建一个扩展方法,但这将是最好的阴影(不是吗?)。我需要正确重写该方法,因为该调用是由仅看到 System
的消费者分派(dispatch)的。
(示例,省略细节)
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)
}
}
最佳答案
只是
trait Mix[A] extends Container[A] with System {
override def isEmpty = elements.isEmpty
}
关于scala - 覆盖两个 mixin 交集中的特征函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68510437/