tsobe
tsobe

Reputation: 179

About lambda syntax

I was examining JDK 8 APIs and inside Function interface I noticed identity function

static <T> Function<T, T> identity() {
    return t -> t;
}

This resolves to method:

R apply(T t);

declared in the same Function interface.

Question is why t -> t part works.

If we expand this expression in terms of familiar Anonymous Inner Class

new Function<String, String>() {

    @Override
    String apply(String t) {
         t; // Oops, compilation error
    }
}

Is t -> t kind of shortcut of t -> { return t; }?

Upvotes: 2

Views: 192

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213351

Question is why t -> t part works.

Because a lambda expression can return the value it takes as parameter. The return is implied in the right part from the target type of the lambda expression. The expression is essentially same as:

t -> { return t; }

That means that t -> t would fail for a functional interface with method that has void return type, as in below case:

Consumer<String> consumer = t -> t;

The target type of lambda there is Consumer<T>, which has the method - void accept(T t) in it. Since the method has void return type, the above assignment fails.

You can go through State of the Lambda for more insight.

Upvotes: 5

Related Questions