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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With