在 Scala 中模拟多重继承

Simulating multiple-inheritance in Scala

我正在做一个基本上需要形式意义上的多重继承的项目:

class X
class Y

class XY extends X,Y

我有两个 classes,它们有一些定义并在整个代码中使用,即:

def alpha(x: X)
def beta(y: Y)

我想动态创建一个 class XY,它只是合并了 XY 中的所有定义,但仍保留类型安全。更具体地说,先前定义的 alphabeta 仍然接受合并后的 class.

我知道 Scala 允许混合特征,例如:

trait T
class A

val ta = new A with T

效果很好。

但是,我不能用 classes:

class X
class Y

val xy = new X with Y

因为 with .. 必须是特征。

我尝试通过执行以下操作来规避此问题:

trait xV extends X
trait yV extends Y

val xy = new xV with yV

不幸的是,这不起作用并出现以下错误:

Error:(33, 26) illegal inheritance; superclass X
 is not a subclass of the superclass Y
 of the mixin trait yV
    val xy = new xV with yV

如有任何帮助,我们将不胜感激。

编辑:

澄清一下,我不能修改class是XY

Scala 没有多重继承 C++ 风格,以避免可怕的 Diamond Shape 继承模式。

Scala提供的(唯一的)solution就是以Trait的形式提供mixins。为了解决方法实现冲突,选择最后实现的 Trait(最右边的那个)。

因此,除非 XY 中至少有一个是 Trait,A 将无法从两者继承(方法)

从字面上看是不可能的。但是

More specifically that the previously defined alpha and beta still accept this merged class.

这个特定的要求可以通过使用隐式转换来实现:

class XY {
  val x = new X
  val y = new Y
}

object XY {
  implicit def toX(xy: XY): X = xy.x
  implicit def toY(xy: XY): Y = xy.y
}

您还可以直接调用 XY 的方法。

但是例如xy match { case x: X => ... 将不匹配,同样 xy.isInstanceOf[X] 将为假。如果 XY 覆盖任何 Object 方法:equalshashCodetoString,它们将不会被 XY.