MapOf vs mutableMapOf in Kotlin: Key Differences and Usage
mapOf creates an immutable map that cannot be changed after creation, while mutableMapOf creates a mutable map that allows adding, removing, or updating entries. Use mapOf when you want a fixed map and mutableMapOf when you need to modify the map later.Quick Comparison
Here is a quick side-by-side comparison of mapOf and mutableMapOf in Kotlin.
| Feature | mapOf | mutableMapOf |
|---|---|---|
| Mutability | Immutable (read-only) | Mutable (modifiable) |
| Modification | Not allowed after creation | Allowed (add, remove, update) |
| Return Type | Map | MutableMap |
| Use Case | Fixed data sets | Dynamic data sets |
| Performance | Slightly faster for read-only | Slightly slower due to mutability support |
| Syntax Example | mapOf("a" to 1) | mutableMapOf("a" to 1) |
Key Differences
mapOf returns an immutable Map instance. This means once you create it, you cannot add, remove, or change any key-value pairs. It is useful when you want to ensure the map stays constant throughout your program, which can help avoid bugs related to accidental changes.
On the other hand, mutableMapOf returns a MutableMap, which supports modification operations like put, remove, and updating values by key. This is helpful when your data needs to change dynamically during runtime.
Both functions take pairs of keys and values as arguments, but their returned types differ in mutability. Choosing between them depends on whether you want to allow changes after creation.
Code Comparison
Here is how you create and try to modify a map using mapOf. Notice that modification is not allowed.
val readOnlyMap = mapOf("apple" to 1, "banana" to 2) println(readOnlyMap["apple"]) // readOnlyMap["apple"] = 3 // Error: Val cannot be reassigned // readOnlyMap.put("cherry", 3) // Error: Unresolved reference: put
mutableMapOf Equivalent
Here is the equivalent code using mutableMapOf, which allows modifications.
val modifiableMap = mutableMapOf("apple" to 1, "banana" to 2) println(modifiableMap["apple"]) modifiableMap["apple"] = 3 modifiableMap.put("cherry", 4) println(modifiableMap)
When to Use Which
Choose mapOf when you have a fixed set of key-value pairs that should not change, such as configuration constants or lookup tables. This ensures safety and can improve performance by preventing accidental modifications.
Choose mutableMapOf when your map needs to change over time, like collecting user input, caching data, or building a map dynamically. It provides flexibility to add, update, or remove entries as needed.
Key Takeaways
mapOf creates an immutable map that cannot be changed after creation.mutableMapOf creates a mutable map that supports adding, removing, and updating entries.mapOf for fixed data and mutableMapOf for dynamic data.