Mutable vs Immutable Map in Kotlin: Key Differences and Usage
Map is immutable by default, meaning you cannot change its contents after creation. A MutableMap allows you to add, remove, or update entries after it is created, providing flexibility to modify the map.Quick Comparison
Here is a quick side-by-side comparison of immutable and mutable maps in Kotlin.
| Feature | Immutable Map (Map) | Mutable Map (MutableMap) |
|---|---|---|
| Modification | Not allowed after creation | Allowed (add, remove, update) |
| Interface | Map | MutableMap extends Map |
| Methods to change | No methods like put or remove | Has put, remove, clear |
| Thread safety | Generally safer as it cannot change | Needs care if shared across threads |
| Use case | Fixed data, read-only access | Dynamic data, needs updates |
Key Differences
An immutable Map in Kotlin is a collection that holds key-value pairs but does not allow any changes once it is created. You cannot add new entries, remove existing ones, or update values. This makes it safe to share and use when you want to guarantee the data stays the same.
On the other hand, a MutableMap extends the Map interface and adds functions like put(), remove(), and clear(). These allow you to change the map's contents after creation. This flexibility is useful when you need to build or update the map dynamically during program execution.
Because MutableMap can change, it requires more care in multi-threaded environments to avoid unexpected behavior. Immutable maps are simpler to reason about since their data never changes.
Code Comparison
Here is how you create and try to modify an immutable map in Kotlin:
fun main() {
val immutableMap: Map<String, Int> = mapOf("apple" to 1, "banana" to 2)
println("Original immutable map: $immutableMap")
// The following line would cause a compile error:
// immutableMap["apple"] = 3
}MutableMap Equivalent
Here is how you create and modify a mutable map in Kotlin:
fun main() {
val mutableMap: MutableMap<String, Int> = mutableMapOf("apple" to 1, "banana" to 2)
println("Original mutable map: $mutableMap")
mutableMap["apple"] = 3 // Update value
mutableMap["cherry"] = 4 // Add new entry
println("Modified mutable map: $mutableMap")
}When to Use Which
Choose an immutable Map when your data should not change after creation, such as configuration settings or fixed lookup tables. This ensures safety and simplicity.
Choose a MutableMap when you need to build or update the map dynamically, like caching results or collecting data during program execution. Just be mindful of thread safety if used in concurrent code.
Key Takeaways
Map) cannot be changed after creation, ensuring data safety.MutableMap) allow adding, removing, and updating entries.MutableMap extends Map, adding modification methods.