为什么在Eclipse中使用类型推理编译的这个java 8示例? [英] Why didn't this java 8 example using type inference compile in Eclipse?

查看:106
本文介绍了为什么在Eclipse中使用类型推理编译的这个java 8示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读新发布的Java 8 in Action,发现第5章中有一段代码没有编译:

I am reading the newly released Java 8 in Action and found there is a piece of code pasted from Chapter 5 not compiling:

    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说:类型不匹配:无法转换 List< Object> 列表< int []>

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

与作者比较后在Github上给出了以下编译:

And after comparing with what the author gave on Github, 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());

唯一的变化是从j到(整数j)。

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

但是,第一个版本是不是完全等同于Java 8提供的语法糖的第二个版本?为什么Java拒绝编译它?

But isn't the first version completely equivalent to the second with the syntax sugar provided by Java 8? Why does Java refuse to compile it?

谢谢

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)


推荐答案

首先,纠正你的术语:当你说语法糖时,你真正要问的是类型推断,当被要求推断出一种类型时对于内部lambda中的 j ,编译器无法提供正确的类型。

First, correcting your terminology: when you say syntax sugar, what you really are asking about is type inference, that when asked to infer a type for j in the inner lambda, that the compiler fails to come up with the right type.

其次,更正您的数据:您引用的错误消息不是来自JDK编译器;他们来自Eclipse。

Second, correcting your data: The error messages you cite are not coming from the JDK compiler; they're coming from Eclipse.

这只是一个Eclipse bug。参考编译器(来自Oracle JDK的 javac )处理你的第一个例子就好了。

This is just an Eclipse bug. The reference compiler (javac from Oracle JDK) handles your first example just fine.

这篇关于为什么在Eclipse中使用类型推理编译的这个java 8示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆