`fun <K, V> Array<K>.associateWith(valueSelector: ...
# stdlib
h
fun <K, V> Array<K>.associateWith(valueSelector: (K) -> V): Map<K, V>
why is this not in stdlib already? i'm very confused. all other versions of associate from
Iterable
exist on
Array
except this one. my use case:
Copy code
myEnumClass.values().associateWith { ... }
i
https://youtrack.jetbrains.com/issue/KT-30372 A workaround is to call
asList()
on the array.
h
does
asList
have significant overhead?
and considering it's weird that
Array
doesn't have this method like one would expect, doesn't it beg the question "why did this person cast this array to list?" whenever you perform the operation this way?
i just wrote my own:
Copy code
fun <K, V> Array<K>.associateWith(valueSelector: (K) -> V): Map<K, V> = associate { it to valueSelector(it) }
i
does
asList
have significant overhead?
No, far less overhead than turning each item into a pair
h
okay, thanks
so i should rewrite as:
Copy code
fun <K, V> Array<K>.associateWith(valueSelector: (K) -> V): Map<K, V> = asList().associateWith(valueSelector)
i
Sure, that would be fine
b
does
asList
have significant overhead?
One easy way to see that it doesn’t is to remember the difference of
asXXX
and
toXXX
in the stdlib.
asXXX
always creates a wrapper which normally has a minimal overhead.
toXXX
on the other hand creates a copy.
👍 4
m
And easy way to figure this out is to press Ctcl+B / Ctrl+Click on a function and read its source code. Sources are just great, a tool #1 to understand what really happens.