Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 940
Noozen Avatar asked Jul 16 '16 03:07

Noozen


People also ask

What is lower bounded wildcard?

A lower bounded wildcard is expressed using the wildcard character ('? '), following by the super keyword, followed by its lower bound: <? super A>. Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.

What happens when we use a bounded wildcard?

We use the Lower Bounded wildcards to widen the use of the type of variable. For example, if we want to add the list of integers in our method we can use the List<Integer>, but using this we will be bound to use only the list of integers.

What are the key differences between upper bounded wildcard and lower bounded wildcard?

The difference is on the compiler side. On the first one you can use the type (to cast something or use it as a bound to call another method for example) while on the second one, you cannot use it.

What is a bounded wildcard?

A bounded wildcard is one with either an upper or a lower inheritance constraint. The bound of a wildcard can be either a class type, interface type, array type, or type variable. Upper bounds are expressed using the extends keyword and lower bounds using the super keyword.


1 Answers

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);
like image 139
Alex - GlassEditor.com Avatar answered Oct 03 '22 19:10

Alex - GlassEditor.com