

Use this one whenever you need to modify the contents of your map. In Kotlin there’s a second interface, MutableMap, that offers write operations. Having said that, you do have to build mutable objects sometimes. You should use immutable objects as much as possible. They’re less prone to accidental mistakes. Why is that? Immutable objects are easier to reason about. For instance, the seminal book Effective Java recommends it.

Reducing the mutability of objects is a best practice. What does that mean? Once you initialize an instance of a map, you can’t change it anymore. Interestingly, the standard interface for maps in Kotlin is immutable. However, you should know that most default constructors create hash tables ( LinkedHashMap in Java, for example). Typically, you’ll use a hash table unless you need to iterate over the keys in order.įor this article, the implementation isn’t relevant because the interface doesn’t change. However, it keeps the keys sorted according to their natural order. The performance isn’t as good as hash tables.
