lambda expression for Consumer Interface with return type

Jaragon :

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.

Naman :

The return type of the single abstract method defined within the FunctionalInterface defines the way the lambda is inferred. For example, the Consumer<String> in the example shared could be represented as an anonymous class such as:

// Consumer<String> consumer = s -> s.isEmpty();
Consumer<String> consumer = new Consumer<String>() {
    @Override
    public void accept(String s) {
        s.isEmpty(); // treated as void here 
    }
};

The same lambda expression when represented as a Predicate<String> could be converted to an anonymous class such as:

// Predicate<String> predicate = s -> s.isEmpty();
Predicate<String> predicate = new Predicate<String>() {
    @Override
    public boolean test(String s) {
        return s.isEmpty(); // returns boolean here
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164890&siteId=1