格继承下的 Scala 内部类型
Scala inner type under lattice inheritance
考虑以下代码:
trait A {
trait T
def t: T
}
trait B1 extends A {
trait T extends super.T
def t: T
}
trait B2 extends A {
trait T extends super.T
def t: T
}
trait C extends B1 with B2 {
trait T extends super.T // super.T means only B2.T, not B1.T
//trait T extends B1.T with B2.T // Actually I want to do this
def t: T
}
这将发生编译错误,因为特征 C
中的类型 T
不继承 B1.T
。但是在特征 C
中,我无法通过调用 super.T
来获得 B1.T
。我该如何解决这个问题?
通过在B1
中定义一个type T1
,我可以解决这个问题:
trait A {
trait T
def t: T
}
trait B1 extends A {
trait T extends super.T
protected type T1 = T
def t: T
}
trait B2 extends A {
trait T extends super.T
def t: T
}
trait C extends B1 with B2 {
trait T extends super.T with T1
def t: T
}
在 Scala 中你可以引用你想要的特定超类:
trait C extends B1 with B2 {
trait T extends super[B1].T with super[B2].T
def t: T
}
考虑以下代码:
trait A {
trait T
def t: T
}
trait B1 extends A {
trait T extends super.T
def t: T
}
trait B2 extends A {
trait T extends super.T
def t: T
}
trait C extends B1 with B2 {
trait T extends super.T // super.T means only B2.T, not B1.T
//trait T extends B1.T with B2.T // Actually I want to do this
def t: T
}
这将发生编译错误,因为特征 C
中的类型 T
不继承 B1.T
。但是在特征 C
中,我无法通过调用 super.T
来获得 B1.T
。我该如何解决这个问题?
通过在B1
中定义一个type T1
,我可以解决这个问题:
trait A {
trait T
def t: T
}
trait B1 extends A {
trait T extends super.T
protected type T1 = T
def t: T
}
trait B2 extends A {
trait T extends super.T
def t: T
}
trait C extends B1 with B2 {
trait T extends super.T with T1
def t: T
}
在 Scala 中你可以引用你想要的特定超类:
trait C extends B1 with B2 {
trait T extends super[B1].T with super[B2].T
def t: T
}