通用方法上界未经检查

huangapple go评论60阅读模式
英文:

Generic method upper bound isn't checked

问题

我创建了一个带有两个类型参数的通用方法,如下所示,位于非通用类内部:

static <T, V extends T> boolean testMethod(T t, V[] v) {
    return true;
}

第二个类型参数定义为 V extends T

现在考虑使用以下参数调用此方法:

testMethod("text", new Integer[]{1, 2});

当我尝试使用上述参数调用此方法时,我预期会得到类型不匹配的错误,因为类型参数 T 被替代为 String,而 V 被替代为 Integer,如您所见,V 受到了 T 的限制,这意味着它必须是 String 类型或其派生类之一,但 Integer 不是它们之一。但是,这段代码编译并成功运行,没有任何问题。

有人能解释一下我对这个概念的印象错在哪里吗?

英文:

I've created a generic method with two type paremeter as follow inside a non-generic class:

static &lt;T, V extends T&gt; boolean testMethod(T t, V[] v) {
    return true;
}

The second type parameter defined as V extends T.

Now consider calling of this method by following arguments:

testMethod(&quot;text&quot;, new Integer[]{1, 2});

When I try to call this method with the above parameters I expected to got an error of type mismatch, because type parameter T substituted by String and V substituted by Integer and as you see V is bounded by T which means it must be of type String or its derived classes but Integer is non of them. But the code segment compile and run successfully without any problem.

Can somebody explain what is wrong about my impression of this concept?

答案1

得分: 8

在这个方法调用中,TV 类型参数的值没有明确提供,因此编译器会自动推断它们。即使结果有时并不直观,它也会尝试推断出有效的替代项而不返回错误。在这个例子中,值 "text" 是一个 String,但它也是一个 Object。由于推断 T = String, V = Integer 是无效的,因为 Integer 不是 String 的子类型,所以编译器使用 T = Object, V = Integer,这是有效的。

英文:

In this method call, the values of the T and V type parameters are not provided explicitly, so the compiler infers them. It will always try to infer valid substitutions before returning an error, even if the results are not always intuitive. In this example, the value “text” is a String, yes, but it is also an Object. Since the inference T = String, V = Integer is invalid because Integer is not a subtype of String, the compiler uses T = Object, V = Integer, which is valid.

huangapple
  • 本文由 发表于 2023年7月10日 19:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定