When building a map, which of these two guidelines...
# stdlib
k
When building a map, which of these two guidelines do you think is better: 1. Use
mapOf
unless it has to be a hashmap, in which case use
hashMapOf
. 2. Use
mapOf
to document to your readers that entry order is important, or
hashMapOf
to document that order doesn't matter.
1️⃣ 5
r
Use the more general unless there is a good reason to use the more specific.
mapOf
is the most general Map creation function. It's a convenience that
mapOf
returns a
LinkedHashMap
, it's deliberately typed to return just a
Map
- if you need to document that you explicitly rely on insertion order you could use
linkedMapOf
. (Incidentally while it's not in the common Kotlin type system, in practice on all three platforms, JS, JVM & Native,
LinkedHashMap
is a subtype of or alias for
HashMap
.)
👆 1
k
Thanks, Rob. Btw can you elaborate on your last sentence:
in practice on all three platforms, JS, JVM & Native, LinkedHashMap is a subtype or alias for HashMap.
I'm not sure what you mean.
r
Have a look at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-linked-hash-map/ In kotlin common,
kotlin.collections.LinkedHashMap : kotlin.collections.MutableMap
, so it's not guaranteed to be a
HashMap
in all circumstances. However, in practice there are only 3 Kotlin platforms, JVM, JS & Native, and on those: • On the JVM
kotlin.collections.LinkedHashMap
is an alias for
java.util.LinkedHashMap
, and
java.util.LinkedHashMap extends java.util.HashMap
. On the JVM
kotlin.collections.HashMap
is an alias for
java.util.HashMap
• On JS,
class kotlin.collections.LinkedHashMap : kotlin.collections.HashMap
• On native,
typealias kotlin.collections.LinkedHashMap = kotlin.collections.HashMap
k
I see what you mean. We can use LinkedHashMap wherever a HashMap is required, but it does have a very slight overhead (i.e. the links) which may not be required, but in most circumstances the overhead can be ignored.