【问题标题】:Override trait function in the intersection of two mixins在两个 mixin 的交集处覆盖 trait 函数
【发布时间】:2021-10-01 05:53:57
【问题描述】:

问题是,当实现两个已知特征时,是否有任何方法(不涉及反射黑魔法)隐式覆盖方法?

假设我们有一个类SysImpl 实现了两个mixin:SystemContainer

// 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 方法,以防SystemContainer[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


【解决方案1】:

只是

  trait Mix[A] extends Container[A] with System {
    override def isEmpty = elements.isEmpty
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多