scala - 覆盖两个 mixin 交集中的特征函数

标签 scala overriding traits mixins implicit

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

认为我们有一个类SysImpl,它实现了两个mixins: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 方法,以防 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/

相关文章:

scala - `forever` 组合器上的 StackOverflow

scala - 示例 Simple IO Type 如何消除 "FP in Scala"中的副作用?

json - Play Framework : How to serialize/deserialize an enumeration to/from JSON

java - 在不调用所需的初始化方法的情况下防止子类实例化的正确方法?

generics - 如何避免将具体结构更改为通用结构所产生的链式 react ?

scala - 如何将特征混合到实例中?

scala - 如何有效地从单个字符串列RDD中提取多个列?

Java:强制子类覆盖父类(super class)的方法

java - Java中的方法覆盖

oop - 了解 Kotlin 中的特征