Kotlin has a `Map/MutableMap` which is a `LinkedHa...
# getting-started
s
Kotlin has a
Map/MutableMap
which is a
LinkedHashMap
which preserves the insertion order unlike
HashMap
. In Java/Android, if one is used to using
HashMap
then I would think I can continue using
Map/MutableMap
in Kotlin. Is that correct?
d
Yes, both
LinkedHashMap
and
HashMap
implement
MutableMap
, which extends
Map
.
s
Thanks. In that case, I will use
LinkedHashMap
. Although I don't think I need to maintain order but I might as well use it.
d
If you don't need order, you should use HashMap, it uses less memory than Linked
👍🏽 1
k
I'm annoyed that
LinkedHashSet
is the default, now everybody is paying this cost all over the code and you need to actively think about using
hashSetOf
instead of
setOf
.
e
I assume the performance cost of LinkedHashMap versus HashMap is completely negligible in 99.9% of all cases. IMHO one should not even think about such micro (nano?) optimizations, but rather spend that effort towards cleaner code with better overall organization.
2
s
Is there no difference between
linkedMapOf(1 to "z")
and
mapOf(1 to "z")
? Or is
LinkedHashMap
a Java class whereas
Map
is Kotlin class, if there is such a thing, and by extension I should use Kotlin specific classes where ever possible.
k
linkedMapOf
always returns a
LinkedHashMap
,
mapOf
returns different types for an empty map. Also ´linkedMapOf` is mutable.
But it's a strange situation, sometimes I use
linkedMapOf
to emphasize that the order matters because
mutableMapOf
clearly doesn't signal that.
s
mapOf
returns different types for an empty map.
What do you mean by different types?
k
Copy code
println(mapOf<String, Int>()::class)
println(mapOf<String, Int>("a" to 0)::class)
println(mapOf<String, Int>("a" to 0, "b" to 1)::class)
println(mapOf<String, Int>("a" to 0, "b" to 1, "c" to 2)::class)

//prints:
//kotlin.collections.EmptyMap
//java.util.Collections$SingletonMap
//java.util.LinkedHashMap
//java.util.LinkedHashMap