Map
In this page:
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
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: