我知道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
有人能解释一下这里发生了什么吗?