All lessons

Maps

8 min · Kotlin

Look up values by key with mapOf and mutableMapOf.

Kotlin · Maps0/5 cleared

Enemy 1 of 5

A List is great when order matters and you look things up by position. Often, though, you want to look something up by a meaningful name instead — a player's username, a product's SKU, a word you're tallying. That's what a Map is for: it stores key-value pairs and lets you retrieve a value quickly given its key, regardless of how many pairs it holds.

You build one with mapOf("key" to value, ...) — the to keyword is Kotlin's readable way of pairing a key with a value (it's actually a small infix function under the hood, not special syntax baked into the language, but you don't need to worry about that detail yet). Once you have a map, you read a value the same way you'd index into a list, but with a key instead of a position: scores["Ada"].

mapOf() creates a read-only map — you can look things up but not add or change entries after creation, matching the listOf() versus mutableListOf() distinction from the Lists lesson.

You
Pincer Crab

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10