Functional Java Generics

The ComputeIfAbsent Map method has the following declaration:

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction).

Why the parameter was not declared as Function<K,V>when the types K and V are not used anywhere else?

Now I understand that K and V are very important, and they are part of the map class declaration.

+4
source share
2 answers

Kand Vare part of the display function type. Therefore, they are actually used. In particular, they define acceptable and most general bounds for the type of the argument and the return type of the display function.

For

Function<? super K,? extends V> mappingFunction

, , , ( , ? super K) , ( extends V). .

: . mappingFunction - Function<? super K,? extends V> Map<K, V> K V.

+4

:

Map<String,Object> myMap = ...
Function<Object,String> myFunc = Object::toString;
myMap.computeIfAbsent("42", myFunc);

?

, myFunc Function<Object,String>, Map<String,Object>, , . , , , Function<K,V>.

, . , , : "42" - String, toString(). String, , , Object. , , .

"" - , Function<? super K, ? extends V>.

+4

Source: https://habr.com/ru/post/1689236/


All Articles