Ellen Spertus
Ellen Spertus

Reputation: 6815

How does java.util.function.Function.compose() work?

The functional interface Function in Java 1.8 implements compose() as shown:

default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
    Objects.requireNonNull(before);
    return (V v) -> apply(before.apply(v));
}

My understanding of lambda expressions (possibly incorrect) is that the above return statement is syntactic sugar for:

    return new Function<V, R>() {
        R apply(V v) {
            return apply(before.apply(v));
        }};

This statement would be illegal because, as an interface, Function<V, R> should not be instantiable. So how does the above method work?

Upvotes: 0

Views: 299

Answers (1)

JB Nizet
JB Nizet

Reputation: 692191

No, it's not syntactic sugar for an anonymous class.

And even if it was, the code you posted doesn't instantiate an interface. It instantiates an anonymous class which implements that interface.

Read the Java tutorial about anonymous inner classes.

Upvotes: 2

Related Questions