在 Java 8 lambda 语法中,大括号何时是可选的?
我意识到Java 8 lambda实现可能会发生变化,但是在lambda构建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
谁能解释一下这里发生了什么?