scala - 以下 'illegal inheritance' (Scala 2.9.2) 背后的原因是什么?

标签 scala inheritance traits type-erasure type-parameter

更新:我用一个更小、更精确的例子重新表述了我的问题。

假设我们有以下定义:

class A
trait TraitForA extends A

class D[T]
trait TraitForD extends D[A]

然后我们可以创建一个对象,例如:

scala> new D[A] with TraitForD
res0: D[A] with TraitForD = $anon$1@145d424

但是我们无法创建以下对象:

scala> new D[A with TraitForA] with TraitForD
<console>:12: error: illegal inheritance;
 anonymous class $anon inherits different type instances of class D:
D[A] and D[A with TraitForA]
             new D[A with TraitForA] with TraitForD
                 ^

当使用 self 类型作为特征而不是 extends 时,也会发生同样的事情:

scala> trait TraitForD2 { self: D[A] => }
defined trait TraitForD2

scala> new D[A with TraitForA] with TraitForD2
<console>:12: error: illegal inheritance;
 self-type D[A with TraitForA] with TraitForD2 does not conform to TraitForD2's
selftype TraitForD2 with D[A]
              new D[A with TraitForA] with TraitForD2
                                           ^

上面的创建(到底)有什么问题?

我的猜测是,D[A with TraitForA] 不被视为类型 D[A]。在类 D 中使用协变注释 +T 时,两个示例都有效。

有人可以解释一下这些示例失败的原因以及为什么它们使用 +T 吗?

额外问题:有没有办法让示例在没有 +T 的情况下运行?

最佳答案

考虑

class C[T]{ def f(t: T): T = t }

C[A with Y] 表示它将有一个 f,它只会采用 A with Y,并且只会返回 A与Y。满足此请求的函数无法满足C[A]。因此两者是矛盾的。

由于类型声明的成功并不取决于所涉及的任何类的方法的细节,Z1 与 Z2 或任何其他组合 C[A]C[A with Y] 一定是一个错误。

关于scala - 以下 'illegal inheritance' (Scala 2.9.2) 背后的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11253770/

相关文章:

scala - 将 JavaScript (d3) 翻译为 Java

以派生类为参数的 C++ 基类构造函数(?)

rust - 如何使用 Arc<Mutex<...>> 转换特征对象?

rust - 如何提供默认的 Debug 实现?

Xcode 和 Scala

scala:在父类和子类中覆盖构造函数中的隐式var?

scala - 如何将大小写与无形变量匹配?

c++ - 类继承链和指向每个类的指针

java - 扩展 View 类

python - 矩阵中单元格之间连接的交互式可视化