Sobes.tech
Junior — Middle

What ways of implementing the Map interface do you know in Kotlin and how do they differ?

sobes.tech AI

Answer from AI

In Kotlin, the Map interface is implemented in several ways, which differ in mutability and internal implementation:

  1. Map (read-only) — an interface for immutable views. Its implementations do not allow modifying the contents. Example of creation:
val map: Map<String, Int> = mapOf("one" to 1, "two" to 2)
  1. MutableMap — extends Map and allows modifying the contents (adding, removing elements). Example:
val mutableMap: MutableMap<String, Int> = mutableMapOf("one" to 1)
mutableMap["two"] = 2
  1. HashMap — a class implementing MutableMap, based on a hash table. Provides fast access by key.

  2. LinkedHashMap — a subclass of HashMap, preserves insertion order of elements.

  3. SortedMap / TreeMap (via Java) — a view where keys are sorted.

Differences:

  • Read-only Map does not allow data modification.
  • MutableMap allows modifications.
  • HashMap is faster but does not guarantee order.
  • LinkedHashMap preserves insertion order.

In Kotlin, the standard functions mapOf and mutableMapOf return, respectively, a read-only Map and a MutableMap, usually implemented via LinkedHashMap.

What ways of implementing the Map interface do you… - sobes.tech