Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

java - 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 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'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...