Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression for Consumer Interface with return type

The thing I don't quite understand is why java compiler allows a lambda expression such as s -> s.isEmpty() inside a consumer interface.

I have tried a lambda expression like s -> s.isEmpty() for a Consumer interface and it works without issue. Some other lambda expressions don't work because they return something, like s -> s.

Consumer<String> cons1 = s -> s.isEmpty();
cons1.accept("abc");

compiles and executes without issue.

So the problem I have is that I thought lambda expressions such as s -> s.isEmpty() were always equivalent to s -> {return s.isEmpty()}; and so I was expecting the compiler to give me an error because you cannot return a boolean (or any other type) from a Consumer Interface. Obviously the compiler is translating the lambda expression into a method were there is no return statement and the method isEmpty() is simply being called without actually returning the value. So the question is When is the return added to the body of the lambda expression? This is so I can know when the compiler will give a compiler error and why.

Thank you very much and sorry if I don't explain myself well enough, I am new here.


1 Answers

It is clearly defined in specification, If the body of a lambda is a statement expression, result will be discarded if return type is void

15.27.3. Type of a Lambda Expression

If the body of a lambda is a statement expression (that is, an expression that would be allowed to stand alone as a statement), it is compatible with a void-producing function type; any result is simply discarded. So, for example, both of the following are legal:

 //Predicate has a boolean result
   Predicate<String> p = s -> list.add(s);

// Consumer has a void result
   Consumer<String> c = s -> list.add(s);

Generally speaking, a lambda of the form () -> expr, where expr is a statement expression, is interpreted as either () -> { return expr; } or () -> { expr; }, depending on the target type.

like image 124
Deadpool Avatar answered Oct 22 '25 13:10

Deadpool