tags:

views:

84

answers:

1

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'

+2  A: 

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.2.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.

Jon Skeet
In case of method overloading, I agree with you that we have to explicitly specify the type. Heck... in Java you can even create one method with particular parameter R and another method that with parameter sub R and it works, so I don't believe the 'confusion' is the problem here.
nanda
your edit solve the question whether the JLS mentioned it, thank you. Now have you any idea 'why' such inference limited only to an assignment?
nanda
@nanda: The first two paragraphs are my guess at the "why" - it keeps the language simpler. Mixing type inference and overloading would be painful. Admittedly the common case would only have a single choice, but special-casing that would be painful too. (C# has a similar issue for type inference when passing method groups to a method taking a delegate, btw.)
Jon Skeet