Skip to content

Instantly share code, notes, and snippets.

@martintreurnicht
Last active October 13, 2016 18:45
Show Gist options
  • Save martintreurnicht/2906b2e1fbfc04d488fbf06219b0746e to your computer and use it in GitHub Desktop.
Save martintreurnicht/2906b2e1fbfc04d488fbf06219b0746e to your computer and use it in GitHub Desktop.
NonNullableMutableMap
interface NonNullableMutableMap<K,V> : MutableMap<K,V> {
override fun get(key: K): V
operator fun set(key: K, value: V) = put(key, value)
}
fun <K,V> MutableMap<K,V>.withoutNullValues(default: () -> V): NonNullableMutableMap<K, V> {
if (this is NonNullableMutableMap) return this
return NonNullableMapWrapper(this, default)
}
class NonNullableMapWrapper<K,V>(val map: MutableMap<K,V>, val default: () -> V) : NonNullableMutableMap<K,V>, MutableMap<K,V> by map {
override fun get(key: K): V = map.getOrPut(key, default)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment