抽象类型中的Scala特征和名称冲突

抽象类型中的Scala特征和名称冲突,scala,traits,abstract-type,Scala,Traits,Abstract Type,我正在尝试定义一个traitC,它扩展了一些traita,B,。。。所有特征,C和A,B,。。。实现一个共同特征T。TraitC应该通过调用A,B trait T{ def f() } trait A extends T{ def f(){ print("A") } } trait B extends T{ def f(){ print("B") } } traitC的预期行为如下: val x=new A with B with C[A,B]{} x.f(

我正在尝试定义一个trait
C
,它扩展了一些trait
a
B
,。。。所有特征,
C
A
B
,。。。实现一个共同特征
T
。Trait
C
应该通过调用
A
B

trait T{
  def f()
}
trait A extends T{
  def f(){
    print("A")
  }
}
trait B extends T{
  def f(){
    print("B")
  }
}
trait
C
的预期行为如下:

val x=new A with B with C[A,B]{}
x.f()
// should produce output
A
B
在这里,我试图定义trait C,它给出了编译错误:

trait C[A<:T,B<:T] extends T{
  self:A with B =>
  override def f(){
    // error: A does not name a parent class of trait C
    super[A].f()
    // error: B does not name a parent class of trait C
    super[B].f()
  }
}

trait C[A如果您想在trait内部提供一个实现,但也要确保子类实现该定义,那么可以使用
抽象覆盖
组合告诉编译器:

trait T {
  def f()
}
trait A extends T {
  abstract override def f() {
    super.f()
    print("A")
  }
}
trait B extends T {
  abstract override def f() {
    super.f()
    print("B")
  }
}

trait C extends T {
  override def f() {
    // do your work here ...
  }
}

val x = new C with A with B
x.f()
要调用mixin层次结构中的下一个实现,必须添加
super.f()
抽象覆盖
方法调用内部调用。由于这样的超级调用需要现有的实现,因此首先需要创建一个
C
实例,它将
a
B
混合在一起。如果在
a
B
中混合
C
,编译器会抱怨,因为e mixin层次结构从左到右执行,因此无法看到
C
的实现