开发者

Why implicit type inference only works in an assignment?

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 o开发者_如何学运维f 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜