今天我在 Scala 中遇到了一些奇怪的情况,当时我试图改进抽象类型成员的类型边界。
我有两个特征定义类型成员的边界并将它们组合在一个具体的类中。这很好用,但是当与特征组合匹配/转换时,只有两个 TypeBounds 之一是“活动的”,我很难理解为什么......
我试图准备一个例子:
trait L
trait R
trait Left {
type T <: L
def get: T
}
trait Right {
type T <: R
}
现在,如果我将这两个特征结合在一个具体的类中
val concrete = new Left with Right {
override type T = L with R
override def get: T = new L with R {}
}
我可以按预期通过 get 访问我的会员
// works fine
val x1: L with R = concrete.get
但是如果我转换为(左与右)或模式匹配,我将无法再访问该成员。根据顺序,我可以从左或右获得类型边界,但不是两者的组合。
// can only access as R, L with R won't work
val x2: R = concrete.asInstanceOf[Left with Right].get
// can only access as L, L with R won' work
val x3: L = concrete.asInstanceOf[Right with Left].get
我知道 Left with Right 与 Right with Left 不同,但在这两种情况下,两种类型的界限都包括在内,那么为什么我只能让一个工作呢?
谁能解释为什么会这样?