Data Types
Arrays and Lists
Read values from a small typed list.
lists
Lists keep several values in order and can be indexed.
Arrays and Lists
ArraysLists.kt
Replay: real traced execution (multi-file project)
fun main() {
val bonus = 2
val scores = listOf(10, 20, 30)
val first = scores[0]
val adjusted = scores[1] + bonus
val size = scores.size
println("first=$first")
println("adjusted=$adjusted")
println("size=$size")
}
fun main() {
val bonus = 0
val scores = listOf(10, 20, 30)
val first = scores[0]
val adjusted = scores[1] + bonus
val size = scores.size
println("first=$first")
println("adjusted=$adjusted")
println("size=$size")
}
fun main() {
val bonus = 5
val scores = listOf(10, 20, 30)
val first = scores[0]
val adjusted = scores[1] + bonus
val size = scores.size
println("first=$first")
println("adjusted=$adjusted")
println("size=$size")
}
bonus ← 2, scores ← [10, 20, 30], first ← 10, adjusted ← 22, size ← 3
1fun main() {2 val bonus→ 2 = 2 //@bonus=0, 53 val scores→ [10, 20, 30] = listOf(10, 20, 30)4 val first→ 10 = scores[0]105 val adjusted→ 22 = scores[1]20 + bonus26 val size→ 3 = scores.size378 println("first=$first10")9 println("adjusted=$adjusted22")10 println("size=$size3")11}outputfirst=10 adjusted=22 size=3
bonus ← 0, scores ← [10, 20, 30], first ← 10, adjusted ← 20, size ← 3
1fun main() {2 val bonus→ 0 = 03 val scores→ [10, 20, 30] = listOf(10, 20, 30)4 val first→ 10 = scores[0]105 val adjusted→ 20 = scores[1]20 + bonus06 val size→ 3 = scores.size378 println("first=$first10")9 println("adjusted=$adjusted20")10 println("size=$size3")11}outputfirst=10 adjusted=20 size=3
bonus ← 5, scores ← [10, 20, 30], first ← 10, adjusted ← 25, size ← 3
1fun main() {2 val bonus→ 5 = 53 val scores→ [10, 20, 30] = listOf(10, 20, 30)4 val first→ 10 = scores[0]105 val adjusted→ 25 = scores[1]20 + bonus56 val size→ 3 = scores.size378 println("first=$first10")9 println("adjusted=$adjusted25")10 println("size=$size3")11}outputfirst=10 adjusted=25 size=3
Follow the List
bonusstarts at2.scoresis10,20, and30.first = scores[0]reads10.adjusted = scores[1] + bonusadds20 + 2.- The program prints
first=10,adjusted=22, andsize=3. | bonus | first | adjusted | size | | --- | --- | --- | --- | | 0 | 10 | 20 | 3 | | 2 | 10 | 22 | 3 | | 5 | 10 | 25 | 3 |
Exercise: ArraysLists.kt
Reproduce adjusted=22, then use the pinned bonuses 0 and 5 to predict each adjusted value.