4
我想重写一个抽象的特性成员,这看起来很简单,但实际上并不会编译。Scala:重写一个抽象的具体成员
这里是什么,我试图做一个归结例如:
// 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 {
^
虽然它强制客户端从'sub.x'切换到'sub.y'(如果客户端需要来自'T2'的附加内容),那么这样做会起作用。 – dwickern