3

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 ?

1
  • 4
    t -> t is short for (T t) -> { return t; } Commented Mar 22, 2018 at 9:03

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

but then if I omit static then it will ask me to implement identity method again inside Object creation of Function<T,T>
@PradeepKumarKushwaha You can put that method (either static or not) inside some class. You cannot put a method with a body inside an interface in Java 7.
@Eugene Well, it has the same behavior.
Well, t -> t always evaluates to the same object in the current implementation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.