【问题标题】:Scala traits and name collision in abstract types抽象类型中的 Scala 特征和名称冲突
【发布时间】:2012-12-26 12:11:37
【问题描述】:

我正在尝试定义一个特征 C,它扩展了一些特征 A,B,... 所有特征,C 和 A,B,... 实现一个共同特征T。特征C应该通过在A,B,..中调用T的实现来实现T:

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()
  }
}

我需要在C 方法A.f() 和B.f() 中调用。 有什么解决办法吗?

【问题讨论】:

    标签: scala traits abstract-type


    【解决方案1】:

    如果您想在 trait 中提供实现,同时确保子类实现定义,则可以使用 abstract override 组合告诉编译器:

    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-hierarchy 中的下一个实现,您必须在 abstract override 方法调用中添加一个 super.f() 调用。因为这样的超级调用需要现有的实现,所以您需要创建的第一件事是混合A 和B 的C 实例。如果你在A 或B 中混入C,编译器会报错,因为混入层次结构是从左到右执行的,因此看不到C 的实现。

    【讨论】:

      猜你喜欢
      • 2011-11-19
      • 2011-05-14
      • 2018-08-10
      • 2015-07-30
      • 1970-01-01
      • 2016-08-20
      • 2012-07-10
      • 1970-01-01
      • 2011-01-03
      相关资源
      最近更新 更多