Search code examples
javajava-8functional-interface

What is the purpose of lower bounded wildcard in Function.class?


In Function.class from Java8, we have:

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

Compose accepts:

Function<? super V, ? extends T> before

Rather than:

Function<V, ? extends T> before

Is there any plausible situation in which the fact that "V" is lower bounded matters?


Solution

  • The ? super allows the returned Function's input type (V) to be different from the arguments input type.

    For example, this compiles with the ? super version but not the alternate one.

    Function<Object, String> before = Object::toString;
    Function<String, Integer> after = Integer::parseInt;
    Function<Integer, Integer> composed = after.compose(before);