Pradeep Kumar Kushwaha
Pradeep Kumar Kushwaha

Reputation: 2239

How does this JAVA 8 lambda method work?

This is Java 8 lambda method what is its JAVA 7 equivalent?

public interface Function<T, R> {

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

    R apply(T t);
}

so its simply a JAVA interface but how t -> t is used ?

Upvotes: 3

Views: 86

Answers (1)

Eran
Eran

Reputation: 393811

That lambda expression is equivalent to the following anonymous class instance:

<T> Function<T, T> identity() {
    return new Function<T, T> () {
        public T apply (T t) {
            return t;
        }
    };
}

The lambda expression saves you the need to specify the name of the interface method you are implementing and its argument types, since they are only used to implement functional interfaces, which can have just one abstract method, so by stating the target interface type (Function<T, T> in this example), it's clear which method you are implementing.

Of course, Java 7 has no static interface methods, so you wouldn't be able to include that method inside an interface.

Upvotes: 4

Related Questions