Lists keep related values in order and let code read them by index.

list index List indexes start at zero, so `scores[0]` reads the first value.

Lists

bonus
Lists.kt
Replay: real traced execution (multi-file project)
fun main() {
    val scores = listOf(82, 91, 76)
    val bonus = 5
    val firstScore = scores[0]
    val adjustedScore = scores[1] + bonus

    println("first=$firstScore")
    println("adjusted=$adjustedScore")
}
fun main() {
    val scores = listOf(82, 91, 76)
    val bonus = 0
    val firstScore = scores[0]
    val adjustedScore = scores[1] + bonus

    println("first=$firstScore")
    println("adjusted=$adjustedScore")
}
fun main() {
    val scores = listOf(82, 91, 76)
    val bonus = 10
    val firstScore = scores[0]
    val adjustedScore = scores[1] + bonus

    println("first=$firstScore")
    println("adjusted=$adjustedScore")
}
  1. scores ← [82, 91, 76], bonus ← 5, firstScore ← 82, adjustedScore ← 96

    1fun main() {2    val scores→ [82, 91, 76] = listOf(82, 91, 76)3    val bonus→ 5 = 5 //@bonus=0, 104    val firstScore→ 82 = scores[0]825    val adjustedScore→ 96 = scores[1]91 + bonus567    println("first=$firstScore82")8    println("adjusted=$adjustedScore96")9}
    outputfirst=82
    adjusted=96
  1. scores ← [82, 91, 76], bonus ← 0, firstScore ← 82, adjustedScore ← 91

    1fun main() {2    val scores→ [82, 91, 76] = listOf(82, 91, 76)3    val bonus→ 0 = 04    val firstScore→ 82 = scores[0]825    val adjustedScore→ 91 = scores[1]91 + bonus067    println("first=$firstScore82")8    println("adjusted=$adjustedScore91")9}
    outputfirst=82
    adjusted=91
  1. scores ← [82, 91, 76], bonus ← 10, firstScore ← 82, adjustedScore ← 101

    1fun main() {2    val scores→ [82, 91, 76] = listOf(82, 91, 76)3    val bonus→ 10 = 104    val firstScore→ 82 = scores[0]825    val adjustedScore→ 101 = scores[1]91 + bonus1067    println("first=$firstScore82")8    println("adjusted=$adjustedScore101")9}
    outputfirst=82
    adjusted=101

Follow the List

  1. scores starts as 82, 91, and 76.
  2. bonus starts at 5.
  3. firstScore = scores[0] reads 82.
  4. adjustedScore = scores[1] + bonus adds 91 + 5.
  5. The program prints first=82 and adjusted=96. | bonus | first score | adjusted score | | --- | --- | --- | | 0 | 82 | 91 | | 5 | 82 | 96 | | 10 | 82 | 101 |

Exercise: Lists.kt

Reproduce first=82 and adjusted=96, then try bonus 0 and 10 and predict each adjusted score before running it.