简体   繁体   English

Java 7泛型类型推断:返回值与方法参数

[英]Java 7 generics type inference: return value vs method argument

Why the compiler is able to correctly infer the String type parameter in the case of a function return type. 为什么编译器能够在函数返回类型的情况下正确推断String类型参数。

public class Generics {
    private static List<String> function() {
        return new ArrayList<>();
    }
}

but it fail when the type to infer is a method parameter : 但是当要推断的类型是方法参数时它会失败:

public class Generics {
    public static void main(String[] args) {
        method(new ArrayList<>());
    }    

    private static void method(List<String> list) {

    }
}

The error in this case is : 这种情况下的错误是:

The method method(List<String>) in the type Generics is not applicable 
for the arguments (ArrayList<Object>)

This is one of the places where type inference does not yet work as expected. 这是类型推断尚未按预期工作的地方之一。

Unfortunately that behaviour is perfectly valid and conforming. 不幸的是,这种行为完全有效且符合要求。

The good news is that Java 8 will include improved type inference (JEP 101) , so situations like this should compile just as you'd expect it: 好消息是Java 8将包含改进的类型推断(JEP 101) ,因此像这样的情况应该按照您的预期进行编译:

It seems reasonable that the compiler should be able to infer the type when the result of such a generic method invocation is passed to another method [...]. 当这种泛型方法调用的结果传递给另一个方法时,编译器应该能够推断出类型似乎是合理的[...]。

Unfortunately, this is not allowed in JDK 5/6/7 – the only option available to the programmer is to use an explicit type-argument. 不幸的是,在JDK 5/6/7中不允许这样做 - 程序员可用的唯一选择是使用显式类型参数。

Apart from the direct improvements (ie situations like the ones you mention here), this change is also necessary for being able to use Lambdas (JEP 126) more efficiently (ie without having to type a lot of type information). 除了直接的改进(例如你在这里提到的那些情况)之外,这种改变对于能够更有效地使用Lambdas(JEP 126)也是必要的(即,不必键入大量类型信息)。

在JLS中推断未解析的类型参数的部分相当复杂,但我理解第一种情况的菱形发生在它受到赋值转换的位置 ,而在第二种情况下它发生在方法调用转换中 ,遵循不同的规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM