【问题标题】:Scala: override a concrete member with an abstract oneScala:用抽象成员覆盖具体成员
【发布时间】:2015-06-20 06:24:25
【问题描述】:

我正在尝试用一个抽象的特征成员覆盖一个特征成员,这看起来很简单,但实际上不会编译。

这是我正在尝试做的一个简化示例:

// not my code:
trait Base {
  val x = new T {}
  trait T {}
}

// my code:
trait Sub extends Base {
  // compile error; see below
  override val x: T2

  // this compiles, but doesn't force `Impl` to implement `x`
//  override val x: T2 = null

  trait T2 extends T {
    val someAddition: Any
  }
}

object Impl extends Sub {
  // should be forced to implement `x` of type `T2`
}

这是编译器错误:

Error:(7, 7) overriding value x in trait Sub of type Sub.this.T2;
 value x in trait Base of type Sub.this.T has incompatible type;
 (Note that value x in trait Sub of type Sub.this.T2 is abstract,
  and is therefore overridden by concrete value x in trait Base of type Sub.this.T)
trait Sub extends Base {
      ^

【问题讨论】:

    标签: scala


    【解决方案1】:

    我能想到的一种技术是为抽象成员使用不同的名称,并让具体成员改为调用它。

    trait Sub extends Base {
      val y: T2
      override val x = y
    

    在 Java 领域有一个关于此的 interesting discussion

    【讨论】:

    • 这会起作用,尽管它会强制客户端从sub.x 切换到sub.y(如果客户端需要来自T2 的额外内容)。
    猜你喜欢
    • 2017-03-03
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2011-02-05
    • 2022-11-01
    • 1970-01-01
    相关资源
    最近更新 更多