computeIfAbsent

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

ported from java.util.Map.computeIfAbsent()

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

If the mapping function returns null, no mapping is recorded. If the mapping function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most common usage is to construct a new object serving as an initial mapped value or memoized result, as in:

 `map.computeIfAbsent(key, k -> new Value(f(k)));
`
*

Or to implement a multi-value map, Map<K,Collection<V>>, supporting multiple values per key:

 `map.computeIfAbsent(key, k -> new HashSet()).add(v);
`
*

The mapping function should not modify this map during computation.

Return

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

Since

1.8

Parameters

key

key with which the specified value is to be associated

mappingFunction

the mapping function to compute a value

Throws

if the specified key is null and this map does not support null keys, or the mappingFunction is null

if the computeIfAbsent operation is not supported by this map (-restrictions optional)

if the class of the specified key or value prevents it from being stored in this map (-restrictions optional)

if some property of the specified key or value prevents it from being stored in this map (-restrictions optional)