James Whitehead
09/20/2021, 5:41 AMprivate val registry: MutableMap<String, MutableSet<EventListener<*>>> = hashMapOf()
2.
private val registry = hashMapOf<String, MutableSet<EventListener<*>>>()
Jacob
09/20/2021, 5:53 AMManuel Dossinger
09/20/2021, 7:09 AMMutableMap
, as you specified, in the second it's a HashMap
. Slight difference.
If you do not really insist on having a hashMap, I'd say, the most idiomatic is
3.
private val registry = mutableMapOf<...>()
Tomasz Krakowiak
09/20/2021, 7:21 AMJames Whitehead
09/20/2021, 9:12 AMhho
09/20/2021, 9:40 AMmutableMapOf
returns a LinkedHashMap
as opposed to a regular HashMap
for hashMapOf
. So the tradeoff seems to be a little more memory usage, but the insertion order is preserved for iteration.James Whitehead
09/20/2021, 9:45 AMTomasz Krakowiak
09/20/2021, 9:50 AMmutableMapOf
as long it's reasonable (O(log n) get
and put
). As @hho said unless you require hash map specifically(due to for example resources/time constraints), you should just say "give me mutable map". If for example you would need to preserve insertions order, than you should say "give me `LinkedHashMap`" or even better "give me map, that preserves order", but you should not use mutableMapOf
despite it's implemented to return LinkedHashMap
as there's not contract that mutableMapOf
would return map that preserves order and it would be not clear for the person reading the code, that your code depends on preserving-order contract.hho
09/20/2021, 9:51 AMmutableMapOf
state that the iteration order is preserved.Tomasz Krakowiak
09/20/2021, 9:51 AMLinkedHashMap
, as mutableMapOf
is usually used to express "give me any map" and doesn't really explicitly implies dependency of the order-preserving contract.Manuel Dossinger
09/20/2021, 10:39 AMephemient
09/25/2021, 6:34 PM