Hi often find myself having a mutableMap where the...
# stdlib
x
Hi often find myself having a mutableMap where the values are mutable collections, and so I created this extension :
Copy code
fun <K, V> MutableMap<K,V>.getOrCreate(key : K, create : ()->V?) : V? {
    return if (containsKey(key) ) {
        get(key)
    } else {
        put(key, create())
    }
}
f
You have
getOrDefault
and
getOrPut
in the stdlib for exactly that. 🙂 The only difference in your example is that your
create
function is allowed to create something that is nullable and (naturally) your function is allowed to return something nullable. However, your map does not necessarily allow that. I recommend the stdlib variants. 😉
x
thanks 🙂
Getting into the source code, It'd be also nice to have a
getOrPutImplicitDefault
🙂
That way I could create the mutableMap
.withDefault()
and avoid passing the lambda each time
f
You can add that through an extension function. 😉
t
The return value of
put
is the previous value in the map. In your case this is always null. Is that expected in your code?