Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala:用抽象成员覆盖具体成员_Scala - Fatal编程技术网

Scala:用抽象成员覆盖具体成员

Scala:用抽象成员覆盖具体成员,scala,Scala,我试图用一个抽象成员覆盖trait成员,这看起来很简单,但实际上不会编译 下面是我试图做的一个简单的例子: // 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

我试图用一个抽象成员覆盖trait成员,这看起来很简单,但实际上不会编译

下面是我试图做的一个简单的例子:

// 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 {
      ^

我能想到的一种技巧是为抽象成员使用不同的名称,让具体成员调用这个名称

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

Java land中有一个关于这一点的问题。

这会起作用,尽管它会强制客户机从
sub.x
切换到
sub.y
(如果客户机需要
T2
中的其他内容)。