Xavier F. Gouchet
02/14/2020, 7:19 AMfun <K, V> MutableMap<K,V>.getOrCreate(key : K, create : ()->V?) : V? {
return if (containsKey(key) ) {
get(key)
} else {
put(key, create())
}
}
Fleshgrinder
02/14/2020, 7:27 AMgetOrDefault
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. 😉Xavier F. Gouchet
02/14/2020, 8:12 AMgetOrPutImplicitDefault
🙂.withDefault()
and avoid passing the lambda each timeFleshgrinder
02/14/2020, 8:21 AMThomas
02/14/2020, 3:09 PMput
is the previous value in the map. In your case this is always null. Is that expected in your code?