为什么Java的类型推断如此薄弱? [英] Why is Java's type inference so weak?

查看:110
本文介绍了为什么Java的类型推断如此薄弱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个方法:

  public static< T>收集和LT; T> addToCollection(T元素,Collection< T>集合){
collection.add(element);
返回集合;
}

然后当试图编译这段代码时:

  Integer i = 42; 
集合<整数> result = addToCollection(i,Collections.emptyList());

我得到一个错误类型不匹配:无法从Collection< Object>收集<整数>
任何人都可以解释为什么类型系统不能推断Collections.emptyList()应该是 Collection< Integer>



上面的例子显然是很人造的,但我总是偶然发现这个限制,这真的很烦人。阅读完 Effective Java 之后,我发现你可以简单地执行 Collections。< Integer> emptyList()(必须说,当时对我来说是一个启示),并且一切都在顺利编译,但是当你有一些复杂的类型时,它确实是一个令人讨厌的东西。



我只是想知道这个是类似的错误,或者是否有任何有效的理由使其以这种方式工作? 解决方案

类型推断系统已在Java 8中进行了改进,并引入了目标打字,以便给溪流和lambda表达更多的表现力。因此,您的代码将与Java 8一起编译。



有关它的更多信息,请参见更新教程,在页面的最底部有一个非常类似的例子。


Say, I have a method:

public static <T> Collection<T> addToCollection(T element, Collection<T> collection) {
    collection.add(element);
    return collection;
}

And then when trying to compile this code:

Integer i = 42;
Collection<Integer> result = addToCollection(i, Collections.emptyList());

I get an error Type mismatch: cannot convert from Collection<Object> to Collection<Integer>. Could anyone explain why the type system cannot infer that Collections.emptyList() should be of type Collection<Integer>?

The example above is obviously quite artificial, but I stumble upon that limitation all the time and it's really annoying. After having read Effective Java I have found out that you can simply do Collections.<Integer>emptyList() (must say, that was quite a revelation for me at the time) and have everything compiling smoothly, but when you have some complicated type then it really is a nuisance.

I'm just wondering if this is some sort of bug, or are there any valid reasons for it to work that way?

解决方案

The type inference system has been improved in Java 8, with the introduction of target typing, in order to give more expressivity to streams and lambdas. As a consequence your code compiles with Java 8.

More about it in the updated tutorial, with a very similar example towards the very bottom of the page.

这篇关于为什么Java的类型推断如此薄弱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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