我意识到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); });
}
}
Run Code Online (Sandbox Code Playgroud)
但删除这样的大括号:
names.filter(e -> e.length() > 4).forEach(e -> System.out.println(e));
Run Code Online (Sandbox Code Playgroud)
给出了错误
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 …Run Code Online (Sandbox Code Playgroud)