Look up a value by key with a fallback.

map A map stores values under keys.

Map Basics

code
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")
}
  1. 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
  1. 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
  1. 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

  1. The map stores A -> 10 and B -> 7.
  2. code is A.
  3. points[code] returns 10.
  4. The Elvis fallback ?: 0 would handle a missing key.
  5. score > 0 makes found true. | 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