我一直认为,如果需要,类型别名总是会扩展到其原始类型。但是,这是一个麻烦制造者
def a[P](a: Option[P]) = {
type Res = List[P] // result type alias
Nil: Res // Replace this line with Nil: List[P] to clear the error
}
def b[V](v: V) = a(Some(v)): List[V]
它失败(scastie)
error: type mismatch;
found : Res (which expands to) List[P]
required: List[V]
您会看到进行a
转换,Option[P] => List[P]
并且由于b
提供了Some[V]
,因此在调用它时也会进行a
转换。但是,编译器说结果与不兼容。这怎么可能?如果您将替换为,错误就会消失(scastie)。您需要消除类型别名以消除该错误。这意味着类型别名是罪魁祸首。Option[V] => List[V]
b
List[V]
Nil: Res
Nil: List[P]
a
我几乎可以肯定这是一个编译器错误。Scala中的类型别名应该会自动扩展,并且在这种情况下,其类型a
推断为[P](Option[P]) => Res
,而不是[P](Option[P]) => List[P]
。而且由于Res在内部范围内,因此编译器无法找到它来b
正确推断类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句