何时大括号在Java 8 lambda语法中是可选的? [英] When are braces optional in Java 8 lambda syntax?

查看:108
本文介绍了何时大括号在Java 8 lambda语法中是可选的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到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 statement),或者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中,如果值为则返回 ed,那么所有可能的代码路径必须返回一个值或 throw a Throwable

In a block-style lambda, if a value is returned, then all possible code paths must either return a value or throw a Throwable.

这篇关于何时大括号在Java 8 lambda语法中是可选的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆