computeIfAbsent

fun computeIfAbsent(key: K, mappingFunction: (K) -> V?): V?

If the specified key is not already associated with a value (or is mapped to null), computes its value using the given mapping function and enters it into this map unless null.

This implementation matches the Java Map.computeIfAbsent contract:

  • If the mapping function returns null, removes the mapping if present and returns null.

  • If the mapping function returns a non-null value, inserts it and returns it.

  • If the key is already mapped to a non-null value, returns the existing value.

The mapping function may not modify this map during execution, or a ConcurrentModificationException is thrown.

Return

the current (existing or computed) value associated with the key, or null if none

Parameters

key

the key whose associated value is to be computed

mappingFunction

the function to compute a value

Throws

if the map is modified during computation