Nir
12/22/2020, 10:15 PMpublic inline fun <K, V> MutableMap<K, V>.getOrPut(key: K, defaultValue: () -> V): V {
val value = get(key)
return if (value == null) {
val answer = defaultValue()
put(key, answer)
answer
} else {
value
}
}
It seems like either the implementation or the description is wrong:
Returns the value for the given key. If the key is not found in the map, calls the defaultValue function, puts its result into the map under the given key and returns it.
println(mutableMapOf<Int, Int?>(5 to null).getOrPut(5) { 10 })
Prints 10. However, 5 is "in the map" (println(5 in mutableMapOf<Int, Int?>(5 to null)
prints true).
kotlin nulls are very tricky in generic code.Marc Knaup
12/22/2020, 10:38 PMNir
12/22/2020, 10:51 PMNir
12/22/2020, 10:51 PMNir
12/22/2020, 10:51 PMNir
12/22/2020, 10:51 PM