Colton Idle
12/11/2022, 5:04 AMColton Idle
12/11/2022, 5:10 AMJosh Eldridge
12/11/2022, 5:19 AMhashSetOf
is the mutable version so there wouldn't exist a mutableHashSet
, if you wanted an "immutable" set you'd call setOf
which is just a LinkedHashSet
cast to an immutable typeJosh Eldridge
12/11/2022, 5:21 AMJosh Eldridge
12/11/2022, 5:22 AMRob Elliot
12/11/2022, 8:03 AMmutableSetOf
would do wouldn’t it? You don’t care about the implementation.Joffrey
12/11/2022, 2:03 PMSet
(or MutableSet
) is what you want. As for the factory function, just like for lists and maps, use setOf
for a read-only structure, mutableSetOf
for a mutable structure. hashSetOf
, arrayListOf
and the likes are really for cases when the exact implemation matters, which is almost never the caseColton Idle
12/11/2022, 4:07 PMRob Elliot
12/11/2022, 4:22 PMsetOf
and mutableSetOf
both return a LinkedHashMap
LinkedHashSet
under the hood, so they are constant time for contains
(and for add
and remove
in the mutable case).
They would never switch it to an implementation that performs worse in the general case.
Specifying collection implementations is almost certainly premature optimisation based on insufficient information. Use the defaults until you have a proof that you need something else.Colton Idle
12/11/2022, 9:03 PMRob Elliot
12/11/2022, 11:34 PMsetOf
and mutableSetOf
are backed by LinkedHashSet
, not LinkedHashMap
. Sorry.
(Though it could be; implementing Set
using a Map
as you did is supported directly on the JVM - see java.util.Collections.newSetFromMap
. I use that passing it a ConcurrentHashMap
when I want a concurrent mutable set as so: val concurrentSet: MutableSet<String> = Collections.newSetFromMap(ConcurrentHashMap())
)