CypherK
12/05/2018, 8:38 AMclass MapWithDefault<K,V>(val map:Map<K,V>,val default:(K)->V): Map<K,V> by map{
override fun get(key: K): V = map[key] ?: default(key)
}
class MutableMapWithDefault<K,V>(val map:MutableMap<K,V>,val default:(K)->V): MutableMap<K,V> by map{
override fun get(key: K): V = map[key] ?: default(key)
}
/**override standard [Map.withDefault]*/
fun <K,V>Map<K,V>.withDefault(default:(K)->V) = MapWithDefault(this,default)
fun <K,V>MutableMap<K,V>.withDefault(default:(K)->V) = MutableMapWithDefault(this,default)
whenever I want to use a map with default.
Because
val m = mutableMapOf<Char,Int>().withDefault{0}
val foo = m['f']
will result in foo == null, without the imports.
And I never understood why that should be the expected behaviour.