gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:21:48 24 4
gpt4 key购买 nike

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

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

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

有一个 interesting discussion关于这一点在 Java 土地上。

关于Scala:用抽象成员覆盖具体成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com