Collections
Map Basics
Look up a value by key with a fallback.
map
A map stores values under keys.
Map Basics
MapBasics.kt
Replay: real traced execution (multi-file project)
fun main() {
val code = "A"
val points = mapOf("A" to 10, "B" to 7)
val score = points[code] ?: 0
val found = score > 0
println("code=$code")
println("score=$score")
println("found=$found")
}
fun main() {
val code = "B"
val points = mapOf("A" to 10, "B" to 7)
val score = points[code] ?: 0
val found = score > 0
println("code=$code")
println("score=$score")
println("found=$found")
}
fun main() {
val code = "Z"
val points = mapOf("A" to 10, "B" to 7)
val score = points[code] ?: 0
val found = score > 0
println("code=$code")
println("score=$score")
println("found=$found")
}
code ← A, points ← {A=10, B=7}, score ← 10, found ← true
1fun main() {2 val code→ A = "A" //@code="B", "Z"3 val points→ {A=10, B=7} = mapOf("A" to 10, "B" to 7)4 val score→ 10 = points[code]10 ?: 05 val found→ true = score10 > 067 println("code=$codeA")8 println("score=$score10")9 println("found=$foundtrue")10}outputcode=A score=10 found=true
code ← B, points ← {A=10, B=7}, score ← 7, found ← true
1fun main() {2 val code→ B = "B"3 val points→ {A=10, B=7} = mapOf("A" to 10, "B" to 7)4 val score→ 7 = points[code]7 ?: 05 val found→ true = score7 > 067 println("code=$codeB")8 println("score=$score7")9 println("found=$foundtrue")10}outputcode=B score=7 found=true
code ← Z, points ← {A=10, B=7}, score ← 0, found ← false
1fun main() {2 val code→ Z = "Z"3 val points→ {A=10, B=7} = mapOf("A" to 10, "B" to 7)4 val score→ 0 = points[code]null ?: 05 val found→ false = score0 > 067 println("code=$codeZ")8 println("score=$score0")9 println("found=$foundfalse")10}outputcode=Z score=0 found=false
Look Up with Fallback
- The map stores
A -> 10andB -> 7. codeisA.points[code]returns10.- The Elvis fallback
?: 0would handle a missing key. score > 0makesfoundtrue. | Code | Score | Found? | | --- | --- | --- | |A|10|true| |B|7|true| |Z|0|false|
Exercise: MapBasics.kt
Look up a code in a map, fall back to zero, and print whether it was found