Maps help you store pairs of related information, like a name and a phone number. Using mapOf and mutableMapOf lets you create these pairs easily.
0
0
Map creation (mapOf, mutableMapOf) in Kotlin
Introduction
When you want to look up a value by a key, like finding a phone number by a person's name.
When you need to store settings or options with names and values.
When you want to group data where each item has a unique label.
When you want to change or add pairs after creating the map, use a mutable map.
When you only need to read data without changing it, use an immutable map.
Syntax
Kotlin
val mapName = mapOf(key1 to value1, key2 to value2) val mutableMapName = mutableMapOf(key1 to value1, key2 to value2)
mapOf creates a map you cannot change later (immutable).
mutableMapOf creates a map you can add or remove pairs from (mutable).
Examples
This creates an immutable map of color names to their hex codes.
Kotlin
val colors = mapOf("red" to "#FF0000", "green" to "#00FF00")
This creates a mutable map with user information you can update later.
Kotlin
val userInfo = mutableMapOf("name" to "Alice", "age" to 30)
Updates the age in the mutable map to 31.
Kotlin
userInfo["age"] = 31
Sample Program
This program shows how to create an immutable map of country capitals and a mutable map of game scores. It prints the capital of France, then shows the scores before and after updating.
Kotlin
fun main() { val capitals = mapOf("France" to "Paris", "Japan" to "Tokyo") println("Capital of France: ${capitals["France"]}") val scores = mutableMapOf("Alice" to 10, "Bob" to 8) println("Initial scores: $scores") scores["Alice"] = 15 scores["Charlie"] = 12 println("Updated scores: $scores") }
OutputSuccess
Important Notes
Immutable maps cannot be changed after creation; trying to add or remove items will cause an error.
Mutable maps let you add, update, or remove pairs anytime.
Use the to keyword to create pairs inside the map.
Summary
mapOf creates a fixed map you cannot change.
mutableMapOf creates a map you can change later.
Maps store pairs of keys and values for easy lookup.