Search code examples
javadictionarylambdafunctional-programmingweak-references

Incompatible parameter types in lambda expression


Considering this code:

Map<C1, C2> map;
C1 key;
C2 value;

Why does this work:

map.computeIfAbsent(key, k -> value)

And this doesn't?

map.computeIfAbsent(key, () -> value)

Solution

  • Because the method computeIfAbsent has the following signature:

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

    so it expects a Function, which is a function interface that expects an argument and returns a value. Whereas () -> value, receives no arguments and produces a value (e.g., Supplier).