Java 8 lambda 语法中的大括号何时是可选的? [英] When are braces optional in Java 8 lambda syntax?
问题描述
我意识到 Java 8 lambda 实现可能会发生变化,但在 lambda build b39 中,我发现只有当 lambda 表达式返回非 void 类型时才能省略大括号.例如,这会编译:
I realise that the Java 8 lambda implementation is subject to change, but in lambda build b39, I've found that braces can only be omitted when the lambda expression returns a non-void type. For example, this compiles:
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); });
}
}
但是像这样去掉大括号:
But removing the braces like this:
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
谁能解释一下这里发生了什么?
Can anyone explain what's going on here?
推荐答案
当 lambda 主体是单个表达式或 void 方法调用时,您可以省略大括号.每个表达式的计算结果都是一个值,因此不能为空.
You may omit the braces when the lambda body is a single expression or a void method invocation. Every expression evaluates to a value, and thus cannot be void.
如果 lambda 的主体是一个语句块(例如,一系列计算后跟一个 return
语句),或者 lambda 没有值(即有一个 void代码>返回类型)并且不是单一的void方法调用,必须使用块形式,需要括号.
If the body of the lambda is a block of statements (e.g. a series of calculations followed by a return
statement), or the lambda has no value (i.e. has a void
return type) and is not a single void method invocation, you must use the block form, which requires brackets.
在块式 lambda 中,如果一个值是 return
ed,那么所有可能的代码路径必须return
一个值或 throw
一个 Throwable
.
In a block-style lambda, if a value is return
ed, then all possible code paths must either return
a value or throw
a Throwable
.
这篇关于Java 8 lambda 语法中的大括号何时是可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!