Why didn't this java 8 example use type input method in Eclipse?

I read the recently released Java 8 in action and found that there is a piece of code inserted from chapter 5 that is not compiled:

List<Integer> numbers1 = Arrays.asList(1, 2, 3); List<Integer> numbers2 = Arrays.asList(3, 4); List<int[]> pairs = numbers1.stream() .flatMap((Integer i) -> numbers2.stream() .map(j -> new int[]{i, j}) ) .collect(toList()); 

Eclipse says: "Type of mismatch: cannot be converted from List<Object> to List<int[]> "

And after comparing with what the author of Github gave, the following compiled:

  List<Integer> numbers1 = Arrays.asList(1, 2, 3); List<Integer> numbers2 = Arrays.asList(3, 4); List<int[]> pairs = numbers1.stream() .flatMap((Integer i) -> numbers2.stream() .map((Integer j) -> new int[]{i, j}) ) .collect(toList()); 

The only change is from "j" to "(Integer j)".

But is not the first version fully equivalent to the second with syntactic sugar provided by Java 8? Why does Java refuse to compile it?

thanks

BTW:

 java -version java version "1.8.0_20" Java(TM) SE Runtime Environment (build 1.8.0_20-b26) Java HotSpot(TM) Client VM (build 25.20-b23, mixed mode) 
+8
java lambda java-8
source share
1 answer

First, a correction of your terminology: when you talk about syntactic sugar, what you are really asking about is the type inference, that when it is asked to infer the type for j in the inner lambda, that the compiler could not find the correct type.

Secondly, correction of your data: error messages that you quote do not come from the JDK compiler; they come from Eclipse.

This is just an Eclipse error. The link compiler ( javac from Oracle JDK) does a great job with your first example.

+15
source share

All Articles