When are braces optional in Java 8 lambda syntax?

前端 未结 4 2086
一向
一向 2020-11-29 10:23

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

4条回答
  •  情话喂你
    2020-11-29 10:57

    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.

    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.

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

提交回复
热议问题