How to Add Entry to Map in Kotlin: Simple Guide
In Kotlin, you can add an entry to a mutable map using the
put(key, value) function or the indexing operator [key] = value. Immutable maps cannot be changed after creation, so use mutableMapOf() to create a map you can add entries to.Syntax
To add an entry to a mutable map in Kotlin, use either:
map.put(key, value)- adds or updates the entry with the given key.map[key] = value- a shorter, idiomatic way to add or update an entry.
Note that the map must be mutable (created with mutableMapOf()) to add entries.
kotlin
val map = mutableMapOf<String, Int>() map.put("apple", 3) // Using put() map["banana"] = 5 // Using indexing operator
Example
This example shows how to create a mutable map, add entries using both put() and the indexing operator, and print the map contents.
kotlin
fun main() {
val fruitCounts = mutableMapOf<String, Int>()
fruitCounts.put("apple", 3) // Add entry with put()
fruitCounts["banana"] = 5 // Add entry with indexing
println(fruitCounts) // Print the map
}Output
{apple=3, banana=5}
Common Pitfalls
Trying to add entries to an immutable map causes errors. Immutable maps created with mapOf() cannot be changed after creation.
Wrong:
Using mapOf() and then trying to add entries will fail.
kotlin
fun main() {
val map = mapOf("apple" to 3)
// map["banana"] = 5 // Error: Val cannot be reassigned - map is immutable
}Quick Reference
Summary of how to add entries to maps in Kotlin:
| Action | Code Example | Notes |
|---|---|---|
| Create mutable map | val map = mutableMapOf | Map can be changed |
| Add or update entry | map.put(key, value) | Adds or updates key with value |
| Add or update entry (idiomatic) | map[key] = value | Shorter syntax for put() |
| Immutable map | val map = mapOf(key to value) | Cannot add or change entries |
Key Takeaways
Use mutableMapOf() to create a map you can add entries to.
Add entries with map.put(key, value) or map[key] = value syntax.
Immutable maps created with mapOf() cannot be modified after creation.
The indexing operator map[key] = value is the most common way to add or update entries.
Trying to add entries to an immutable map causes compile-time errors.