am i understanding it right that using `withDefaul...
# stdlib
b
am i understanding it right that using
withDefault
for a map doesn't actually insert that default into the map when a key which isn't present is found, it just returns an instance of that default?
n
this is the code for the function:
Copy code
public fun <K, V> Map<K, V>.withDefault(defaultValue: (key: K) -> V): Map<K, V> =
    when (this) {
        is MapWithDefault -> this.map.withDefault(defaultValue)
        else -> MapWithDefaultImpl(this, defaultValue)
    }
so your assumption is correct
b
do you know of an API/idiom to get the other behavior? (insert a initial value the first time a key which isn't present is retrieved)
k
That's just the factory function, you need to look at the
getValue
source @nfrankel
This is so easy to test though:
Copy code
val map = mutableMapOf<String, Int>().withDefault { 5 }
println(map.getValue("test"))
println(map.keys)
No, it doesn't insert it.
b
yes, and i had seen that behavior in code i wrote, i just wanted to double check i wasn't nuts/missing something
k
I see.
b
in my head 'withDefault' strongly suggested it would be inserted, separating it from
getOrDefault
k
For the other behavior you need
getOrPut
although you then have to repeat the default value.
b
great, i had missed
getOrPut
. i think i can live with that, though the other style would've been nice. i run into this somewhat often when having a map of some key to a list
d
A map which inserts when you call
get
violates the
Map
interface contract and thus is a bad idea.
👍 2
b
sure, i'd be fully fine with a separate map type that did this. i'm thinking of
DefaultDict
in python (that was actually my initial interpretation of what
withDefault
did: return me a wrapped map type which had that behavior)
👍 1