当泛型与无界通配符一起使用时,不考虑类型参数绑定 [英] Type parameter bound not considered when generic type is used with unbounded wildcard

查看:60
本文介绍了当泛型与无界通配符一起使用时,不考虑类型参数绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有一个这样的星座:

In my project, I have a constellation like this:

trait F

trait X[A <: F]

def test(x: X[_]): X[_ <: F] = x

Trait X 有一个类型参数,其上限为 F.根据我的理解,类型 X[_]X[_ <: F] 应该是等效的.但是 scalac 2.12.5 抱怨一个不能分配给另一个.

Trait X has a type parameter with an upper bound of F. From my understanding, the types X[_] and X[_ <: F] should be equivalent. But scalac 2.12.5 complains that one is not assignable to the other.

$ scalac -Xscript test test.scala 
test.scala:5: error: type mismatch;
 found   : this.X[_$1] where type _$1
 required: this.X[_ <: this.F]
def test(x: X[_]): X[_ <: F] = x
                               ^

我想不出有什么情况会导致此作业使声音程序变得不健全.这个任务被拒绝的原因是什么?有没有办法允许这样的分配(可能在更复杂的例子中)有问题?

I cannot think of a situation where this assignment is making a sound program unsound. What are the reasons that this assignment is rejected? Is there a way that allowing such an assignment (maybe in a more complex example) is problematic?

推荐答案

这个赋值并不是真的有问题,编译器甚至知道这一点,因为下面的实现编译没有问题:

This assignment isn't really problematic, and the compiler even kind-of knows this, because the following implementation compiles without problems:

trait F
trait X[A <: F]
def test(x: X[_]): X[_ <: F] = x match { case q: X[t] => q }

如果你允许类型检查器为类型变量 t 推断更精确的边界,从而给它一些松弛,它最终会发现 t 必须是F,然后允许您返回值 q(与 x 相同)而不会抱怨.默认情况下它不会这样做出于一些违反直觉的原因可能与 Java 通配符互操作性有关.

If you give the type checker some slack by allowing it to infer more precise bounds for the type variable t, it will eventually figure out that t must be subtype of F, and then allow you to return the value q (which is the same as x) without complaining. It doesn't do this by default for some counter-intuitive reasons that probably have something to do with Java-wildcard interoperability.

(再次取消删除;我最初的猜测似乎并不太远,并且考虑到 Dmytro Mitin 的链接,相比之下,它甚至看起来都不那么模糊.)

(Undeleted again; My original guess didn't seem too far off, and given Dmytro Mitin's link, it doesn't even seem all that vague by comparison.)

这篇关于当泛型与无界通配符一起使用时,不考虑类型参数绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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