为什么这个类型别名不能编译(Scala)



我正试图让以下代码发挥作用:

abstract class Vec[Self <: Vec[Self,T], T] {
    this : Self =>
    def *(y : Self) : Self
}
abstract class LA[T] {
  type V <: Vec[V, T]
}
object typetest2 {
    def doesntcompile[L <: LA[Double]](x : L#V, y : L#V) : Unit = {
        val z = x * y
    }
    def compiles[V <: Vec[V,_]](x : V, y : V) : Unit = {
        val z = x * y
    }
}

但是编译器给出

[error]  found   : y.type (with underlying type L#V)
[error]  required: _9.V
[error]         val z = x * y
[error]                     ^

这是类型检查器失败还是我做错了什么?

虽然我不确定这种特殊情况是否有解决方法,但编译器不能一般地判断两个依赖路径的类型是相等的,即使它们是相等的。

您通常可以通过添加一个额外的类型参数来解决此类情况:

def compiles2[V1 <: Vec[V1, _], L <: LA[Double]{type V = V1}](x: L#V, y: L#V) = {
  val z = x * y
}

在某些情况下,您可能需要隐式=:=Leibniz(Scalaz)来让编译器传递两种类型在链下相等的证据。

最新更新