dimsuz
09/08/2017, 9:20 AMinline fun <K, V> MutableMap<K,V>.replaceOrPut(key: K, updateOp: (V?) -> V): MutableMap<K, V> {
val current = this[key]
this[key] = updateOp(current)
return this
}
Nir
12/01/2020, 9:26 PMinline fun <K, V> MutableMap<K,V>.replaceOrPut(key: K, updateOp: (V?) -> V): MutableMap<K, V> {
val current = this[key]
this[key] = updateOp(current)
return this
}
I prefer to call this function update personally but the idea is the same. It's very useful. Without this I've found it's rather awkward to do certain things in Kotlin; updating for example integers in MutableMap<*, Int> is annoying, you can't even do m["hello"] += 1
This is quite similar to Java hashmaps compute function: https://www.geeksforgeeks.org/hashmap-compute-method-in-java-with-examples/ which is absent in Kotlin's stdlib. Note that Python and C++ to take two examples, allow compound arithmetic on their mutable Maps, so this is fairly awkward relative to quite a number of existing mainstream languages