Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

When are braces optional in Java 8 lambda syntax?

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));

gives the error

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...