Start learning free

LESSON 125 OF 677 · DICTIONARIES

Dictionaries (HashMap) in Kotlin

Lesson

In Kotlin, a Map works like a dictionary — it stores key-value pairs where each key maps to a value. A MutableMap, created with mutableMapOf(), can be changed. No import is needed.

val scores = mutableMapOf<String, Int>()
scores["Alice"] = 95
scores["Bob"] = 87
scores["Charlie"] = 72

The type parameters <String, Int> specify the key type and value type. Use map[key] = value to add entries:

val ages = mutableMapOf<String, Int>()
ages["Alice"] = 25
ages["Bob"] = 30
println(ages["Alice"])  // 25
println(ages.size)      // 2

Assignment
Follow the Coding Tutorial and create a MutableMap named scores with three student scores!


Hint
Declare val scores = mutableMapOf<String, Int>() then use scores[key] = value to add entries.

STEP 1 OF 1
    Ctrl + Enter to check