Java lambda only throwing expression-style instead of statement-style

  • A+
Category:Languages

In Java (using Java 8 currently), I can write this and all will compile nice and well:

Supplier<Long> asd = () -> {     throw new RuntimeException(); }; 

Yet, I cannot write this:

Supplier<Long> asd = () -> throw new RuntimeException(); // This won't compile :( 

Does anyone know why Java's implementation does not allow such style (expression lambda) and only the statement/code-block style lambda?

I mean, since the lambda is only throwing the RuntimeException, why isn't the JDK able to infer the lambda expression as:

new Supplier<Long>() {     @Override     public Long get() {         throw new RuntimeException();     } }; 

Is this documented somewhere in the specs/docs? Is this added only in JDK > 8?

 


From the language spec JLS 15.27.2:

A lambda body is either a single expression or a block (§14.2). 

throw is not a single expression (it's a statement); so you have to use it in a block.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: