Scala类型别名破坏了类型兼容性 [英] Scala type aliasing breaks the type compatibility
问题描述
我一直认为,如果需要,类型别名总是会扩展到其原始类型.但是,这是一个麻烦制造者
I always believed that type aliases always expand to their original type if necessary. But, here is a troublemaker
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
在b
调用时转换了Option[V] => List[V]
.但是,编译器说结果与List[V]
不兼容.这怎么可能?如果将Nil: Res
替换为a
中的Nil: List[P]
,则错误消失( scastie ).您需要消除类型别名以消除该错误.这意味着类型别名是罪魁祸首.
You see that a
converts Option[P] => List[P]
and, since b
supplies Some[V]
, a
converts Option[V] => List[V]
when b
calls it. But, compiler says that result is incompatible with List[V]
. How is this possible? The error goes away (scastie) if you replace Nil: Res
with Nil: List[P]
in the a
. You need to eliminate the type alias to get rid of the error. This means that the type alias is the culprit.
推荐答案
我几乎可以肯定这是一个编译器错误. Scala中的类型别名应该自动扩展,在这种情况下,看起来a
的类型被推断为[P](Option[P]) => Res
而不是[P](Option[P]) => List[P]
.而且由于Res在内部范围内,因此编译器无法找到它来正确推断b
的类型.
I'm almost certain this is a compiler bug. Type aliases in Scala are supposed to automatically expand, and it looks like in this case the type of a
is inferred as [P](Option[P]) => Res
, instead of [P](Option[P]) => List[P]
. And since Res is in an inner scope, the compiler can't find it to infer the type of b
correctly.
这篇关于Scala类型别名破坏了类型兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!