为什么隐式类型推断仅适用于赋值? [英] Why implicit type inference only works in an assignment?
问题描述
我知道在赋值中使用泛型,通过查看左侧变量的类型,方法可以隐式知道返回类型的类型。
Google收集示例:
l = Lists.newArrayList()我的问题是为什么它不适用于方法或更高
List< List< String> ;> ll = Lists.newArrayList();
ll.put(Lists.newArrayList()); //不起作用
这是在JLS中指定的吗?如果是,为什么?如果不是,那么这是我可以从Java 7期望的一种改进吗?
这让我很烦恼,因为看起来我们在Java中遇到了问题,就像我有问题一样Delphi很久以前我不能做链式方法调用,比如:
$ $ $ $ $ $ code $ ab()。c() ;
在Delphi(IIRC)中,您必须这样做:
B b = ab();
C c = b.c();
看起来像'dejavu'
我不想在这里声明特定的知识,但是赋值给一个变量和使用该值作为方法参数之间有一个明显的区别:只有一个可能的 em> target在前一种情况下,该方法是否被重载。
基本上,这意味着您不必担心类型推断和重载/转换交互:推断 only 发生在你知道你感兴趣的唯一目标类型的情况下。
这个是只是一个猜测。我总是发现Java的类型推断很有趣 - 它与C#3完全相反,可以推断出变量的类型(只要它是一个局部变量)。
编辑:我相信相关的 JLS部分是15.12.2.8 :
lockquote
如果方法结果出现在
上下文,它将受到
赋值转换(§5.2)到
S类型,然后让R为声明结果
方法的类型[...]
基本上它是赋值转换位,这很重要。
I know that using generic in an assignment, a method can implicitly know the type of the return type by looking at the type of the left hand side variable.
Example from Google Collection:
List<String> l = Lists.newArrayList()
My question is why it doesn't work for a method or higher type of inference?
Example:
List<List<String>> ll = Lists.newArrayList();
ll.put(Lists.newArrayList()); // doesn't work
Is this specified in the JLS? If yes, why? If no, then is this a kind of improvement that I can expect from Java 7?
This annoyed me because seems that we have a problem in Java like I have problem in Delphi a long time ago where I can't do chained method call like:
C c = a.b().c();
In Delphi (IIRC), you have to do:
B b = a.b();
C c = b.c();
Looks like a 'dejavu'
I wouldn't like to claim particular knowledge here, but there's one obvious difference between assignment to a variable, and using the value as a method argument: there's only one possible target in the former case, whether the method is overloaded or not.
Basically it means that you don't need to worry about type inference and overloading / conversions interacting: the inference only happens in the case where you know the one and only target type you're interested in.
This is just a guess though. I've always found Java's type inference interesting - it works the exact opposite way to C# 3, where you can infer the variable's type (so long as it's a local variable).
EDIT: I believe the relevant JLS section is 15.12.2.8:
If the method result occurs in a context where it will be subject to assignment conversion (§5.2) to a type S, then let R be the declared result type of the method [...]
Basically it's the "assignment conversion" bit which is important.
这篇关于为什么隐式类型推断仅适用于赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!