https://kotlinlang.org logo
Title
s

Sudhir Singh Khanger

10/15/2019, 5:31 AM
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

diesieben07

10/15/2019, 7:03 AM
Yes, both
LinkedHashMap
and
HashMap
implement
MutableMap
, which extends
Map
.
s

Sudhir Singh Khanger

10/15/2019, 8:48 AM
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

diesieben07

10/15/2019, 8:56 AM
If you don't need order, you should use HashMap, it uses less memory than Linked
👍🏽 1
k

karelpeeters

10/15/2019, 8:58 AM
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

eekboom

10/15/2019, 9:25 AM
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

Sudhir Singh Khanger

10/16/2019, 4:19 PM
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

karelpeeters

10/16/2019, 4:23 PM
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

Sudhir Singh Khanger

10/16/2019, 4:41 PM
mapOf
returns different types for an empty map.
What do you mean by different types?
k

karelpeeters

10/16/2019, 4:44 PM
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