【问题标题】:How to force a trait to implement another traits如何强制一个特征实现另一个特征
【发布时间】:2016-09-15 14:06:16
【问题描述】:

我有三个特征,我想强制其中一个称为C 混合特征AB。即使我知道如何强制B 混入A,我也做不到。可以这样做:

trait A {
  def getThree() = 3
}

trait B {
  this: A =>
  def getFive() = 2 + getThree()
}

trait C {
  this: A => // that's the line which 
  // this: B => // this line is incorrect as I there is "this: A =>" already
  // def getEight() = getThree() + getFive() // I want this line to compile
}

因此我可以调用函数getEight()

object App {
  def main(args: Array[String]): Unit = {

    val b = new B with A {}
    println(b.getFive())

    // It would be cool to make these two lines work as well
    // val c = new C with B with A {}
    // println(c.getEight())    
  }
}

【问题讨论】:

  • this: A with B =>

标签: scala multiple-inheritance mixins traits


【解决方案1】:

您可以使用with

trait C {
 self: A with B =>
}

【讨论】:

  • 你能解释一下为什么你用self而不是我的this吗?
  • @GA1 this 用于在上下文中引用当前对象。使用 self 只是为了清楚起见。
  • this 应该在这种情况下使用,因为没有理由引入另一个自类型引用。当您需要区分不同的 this 实例时,使用替代的自类型引用,尤其是在嵌套类的情况下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 2021-12-28
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多