Incompatible parameter types in lambda expression

Viewed 763

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)
2 Answers

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).

In addition to @dreamcrash's answer, there is a way to supply an entry to a Map if the key is absent.

It has been added in and is called Map#putIfAbsent

And this would exactly work like what you had in mind

map.putIfAbsent("key", ((Supplier<String>) () -> "value").get());

However this is a bit complicated and you'd prefer using directly the value

map.putIfAbsent("key", "value");
Related