我意识到 Java 8 lambda 实现可能会发生变化,但在 lambda build b39 中,我发现只有当 lambda 表达式返回非 void 类型时才能省略大括号。例如,这编译:
public class Collections8 {
public static void main(String[] args) {
Iterable<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.filter(e -> e.length() > 4).forEach(e -> { System.out.println(e); });
}
}
但是像这样删除大括号:
names.filter(e -> e.length() > 4).forEach(e -> System.out.println(e));
给出错误
Collections8.java:6: error: method forEach in interface Iterable<T> cannot be applied to given types;
names.filter(e -> e.length() > 4).forEach(e -> System.out.println(e));
^
required: Block<? super String>
found: lambda
reason: incompatible return type void in lambda expression
where T is a type-variable:
T extends Object declared in interface Iterable
谁能解释这里发生了什么?