getOrPutIfMissing

inline fun <K, V> MutableMap<K, V>.getOrPutIfMissing(key: K, crossinline defaultValue: () -> V): V(source)

Returns the value for the given key if the value is present. Otherwise, calls the defaultValue function, puts its result into the map under the given key, and returns the call result.

In contrast to getOrPutIfNull, this function returns the mapped value, even if that value is null.

When the given key is not in this map, the result of defaultValue, even if null, is put into the map under the key. If defaultValue throws an exception, the exception is rethrown.

Note that the operation is not guaranteed to be atomic if the map is being modified concurrently.

Since Kotlin

2.4

Throws

if the specified key or the result of defaultValue is null, and this map does not support null keys or values.

Samples

import kotlin.test.*
import java.util.*

fun main() { 
   //sampleStart 
   val map = mutableMapOf<String, Int?>()

println(map.getOrPutIfMissing("x") { 2 }) // 2
// subsequent calls to getOrPutIfMissing do not evaluate the default value
// since the first getOrPutIfMissing has already stored value 2 in the map
println(map.getOrPutIfMissing("x") { 3 }) // 2

map["x"] = null
// if a key is mapped to null value, getOrPutIfMissing does not overwrite it
println(map.getOrPutIfMissing("x") { 4 }) // null 
   //sampleEnd
}
inline fun <K, V> ConcurrentMap<K, V>.getOrPutIfMissing(key: K, crossinline defaultValue: () -> V): V(source)

Returns the value for the given key if the value is present. Otherwise, calls the defaultValue function, puts its result into the map under the given key, and returns the call result.

In contrast to getOrPutIfNull, this function returns the mapped value, even if that value is null.

When the given key is not in this map, the result of defaultValue, even if null, is put into the map under the key. If defaultValue throws an exception, the exception is rethrown.

This function guarantees not to put the new value into the map if the key is already associated with a value. However, the defaultValue function may still be invoked.

Since Kotlin

2.4

Throws

if the specified key or the result of defaultValue is null, and this concurrent map does not support null keys or values.

Samples

import kotlin.test.*
import java.util.*

fun main() { 
   //sampleStart 
   val map = mutableMapOf<String, Int?>()

println(map.getOrPutIfMissing("x") { 2 }) // 2
// subsequent calls to getOrPutIfMissing do not evaluate the default value
// since the first getOrPutIfMissing has already stored value 2 in the map
println(map.getOrPutIfMissing("x") { 3 }) // 2

map["x"] = null
// if a key is mapped to null value, getOrPutIfMissing does not overwrite it
println(map.getOrPutIfMissing("x") { 4 }) // null 
   //sampleEnd
}