getOrPut
- это функция расширения в MutableMap
Вы можете сделать то же самое для SparseArray
, также используя свою собственную функцию расширения. Вот как удобно Kotlin:)
/**
* Returns the value for the given key. If the key is not found in the SparseArray,
* calls the [defaultValue] function, puts its result into the array under the given key
* and returns it.
*/
public inline fun <V> SparseArray<V>.getOrPut(key: Int, defaultValue: () -> V): V {
val value = get(key)
return if (value == null) {
val answer = defaultValue()
put(key, answer)
answer
} else {
value
}
}