0
0
KotlinHow-ToBeginner · 3 min read

How to Create Map in Kotlin: Syntax and Examples

In Kotlin, you create a map using the mapOf() function for an immutable map or mutableMapOf() for a mutable map. You provide key-value pairs inside parentheses separated by commas, like mapOf("key" to "value").
📐

Syntax

To create a map in Kotlin, use mapOf() for a read-only map or mutableMapOf() for a map you can change later. Inside the parentheses, add key-value pairs using the to keyword.

  • mapOf(): Creates an immutable map.
  • mutableMapOf(): Creates a map you can add or remove entries from.
  • key to value: Defines each pair inside the map.
kotlin
val readOnlyMap = mapOf("apple" to 1, "banana" to 2)
val mutableMap = mutableMapOf("cat" to 3, "dog" to 4)
💻

Example

This example shows how to create both immutable and mutable maps, access values by keys, and add a new entry to the mutable map.

kotlin
fun main() {
    val fruits = mapOf("apple" to 1, "banana" to 2, "orange" to 3)
    println("Fruits map: $fruits")
    println("Value for 'banana': ${fruits["banana"]}")

    val animals = mutableMapOf("cat" to 3, "dog" to 4)
    println("Animals map before adding: $animals")
    animals["bird"] = 5
    println("Animals map after adding: $animals")
}
Output
Fruits map: {apple=1, banana=2, orange=3} Value for 'banana': 2 Animals map before adding: {cat=3, dog=4} Animals map after adding: {cat=3, dog=4, bird=5}
⚠️

Common Pitfalls

One common mistake is trying to add or remove entries from a map created with mapOf(), which is immutable and will cause a runtime error. Another is confusing the syntax by using commas instead of to for key-value pairs.

Always use mutableMapOf() if you need to change the map after creation.

kotlin
/* Wrong: Trying to add to immutable map */
val map = mapOf("a" to 1)
// map["b"] = 2 // Error: Unresolved reference or runtime exception

/* Right: Use mutableMapOf for changes */
val mutableMap = mutableMapOf("a" to 1)
mutableMap["b"] = 2
📊

Quick Reference

FunctionDescriptionMutable
mapOf()Creates an immutable mapNo
mutableMapOf()Creates a mutable mapYes
key to valueSyntax to add key-value pairsN/A

Key Takeaways

Use mapOf() to create a read-only map with key-value pairs.
Use mutableMapOf() if you need to add or remove entries later.
Define pairs using the 'key to value' syntax inside the map functions.
Immutable maps cannot be changed after creation; trying to do so causes errors.
Access map values using square brackets with the key, like map[key].