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
617 views
in Technique[技术] by (71.8m points)

generics - Java 8 and Generalized Target-Type Inference

I have installed the last JDK 8 ea b114 to test the new language features. However the inference in chained calls seems not to work yet.

If I write:

Iterator<String> it = new ArrayList<>().iterator();

the compiler give me an error.

However inference in argument position works well.

Maybe inference in chained calls will not be inserted?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As @Holger said, Java 8 improved contextual inference so that this works_

public static <T> Iterator<T> iter(Iterable<T> i)
{
    return i.iterator();
}

public static void main(String[] args)
{
    Iterator<String> it = iter( new ArrayList<>() );
                \____________________________/
}

It didn't work in Java 7 — the inference on new ArrayList<>() could not depend on context.


It'll be a huge change to the language to do what you want in the question. John Rose started a similar discussion, see http://mail.openjdk.java.net/pipermail/lambda-dev/2013-July/010531.html


Too much inference and too much contextual dependency can be a bad thing. It's not so much that the compiler cannot handle the complexity - it can. It's about whether human programmers can handle it. I am sensing that Java 8 is already at a dangerous level that the codes will be difficult for humans to parse.


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

...