Scala类型别名破坏了类型兼容性 [英] Scala type aliasing breaks the type compatibility

查看:82
本文介绍了Scala类型别名破坏了类型兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为,如果需要,类型别名总是会扩展到其原始类型.但是,这是一个麻烦制造者

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],因此ab调用时转换了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆