Map
A Map links keys to values, like a phone book where a name leads you to a number. You look up a key and get its value quickly.
In this page:
Syntax
val map = Map(key1 -> value1, key2 -> value2)
map(key)
map.get(key)
val updated = map + (key3 -> value3)
Map
A Map stores key-value pairs and gives fast lookup by key, created with Map("a" -> 1, "b" -> 2) using the -> arrow syntax. Map(...) is immutable by default, and keys must be unique.
Accessing a missing key with map(key) throws, so .get(key) (returning an Option) or .getOrElse are the safer alternatives.
Warning:
Accessing a missing key with map(key) throws a NoSuchElementException -- use .get(key) or .getOrElse(key, default) for safety.
Example: Map
object Main extends App {
val ages = Map("Alice" -> 30, "Bob" -> 25)
println(ages("Alice"))
println(ages.getOrElse("Cara", -1))
for ((name, age) <- ages) {
println(s"$name is $age")
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
ages("Cara")for a missing key, which throwsNoSuchElementException; usegetOrElseorget. - Writing
Map("a": 1)with a colon, when the pairs use->. - Expecting
ages + ("Dan" -> 20)to modifyages, when the defaultMapis immutable and returns a new map.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: