Foundations
Collections
Collections keep related values together and let code read values by index.
array index
Array indexes start at zero, so `scores(0)` reads the first value.
Collections
Collections.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val scores = Array(82, 91, 76)
val bonus = 5
val firstScore = scores(0)
val adjustedScore = scores(1) + bonus
println("first=" + firstScore)
println("adjusted=" + adjustedScore)
}
}
object Main {
def main(args: Array[String]): Unit = {
val scores = Array(82, 91, 76)
val bonus = 0
val firstScore = scores(0)
val adjustedScore = scores(1) + bonus
println("first=" + firstScore)
println("adjusted=" + adjustedScore)
}
}
object Main {
def main(args: Array[String]): Unit = {
val scores = Array(82, 91, 76)
val bonus = 10
val firstScore = scores(0)
val adjustedScore = scores(1) + bonus
println("first=" + firstScore)
println("adjusted=" + adjustedScore)
}
}
bonus ← 5, firstScore ← 82, adjustedScore ← 96
1object Main {2 def main(args: Array[String]): Unit = {3 val scores = Array(82, 91, 76)4 val bonus→ 5 = 5 //@bonus=0, 105 val firstScore→ 82 = scores(0)826 val adjustedScore→ 96 = scores(1)91 + bonus578 println("first=" + firstScore82)9 println("adjusted=" + adjustedScore96)10 }11}outputfirst=82 adjusted=96
bonus ← 0, firstScore ← 82, adjustedScore ← 91
1object Main {2 def main(args: Array[String]): Unit = {3 val scores = Array(82, 91, 76)4 val bonus→ 0 = 05 val firstScore→ 82 = scores(0)826 val adjustedScore→ 91 = scores(1)91 + bonus078 println("first=" + firstScore82)9 println("adjusted=" + adjustedScore91)10 }11}outputfirst=82 adjusted=91
bonus ← 10, firstScore ← 82, adjustedScore ← 101
1object Main {2 def main(args: Array[String]): Unit = {3 val scores = Array(82, 91, 76)4 val bonus→ 10 = 105 val firstScore→ 82 = scores(0)826 val adjustedScore→ 101 = scores(1)91 + bonus1078 println("first=" + firstScore82)9 println("adjusted=" + adjustedScore101)10 }11}outputfirst=82 adjusted=101
What Happens
scoresstarts as82,91, and76.bonusstarts at5.scores(0)reads82.scores(1) + bonusadds91 + 5.- The program prints
first=82andadjusted=96.
Collection Picture
| bonus | first value | adjusted value | | --- | --- | --- | | 0 | 82 | 91 | | 5 | 82 | 96 | | 10 | 82 | 101 |
Exercise: Collections.scala
Reproduce first=82 and adjusted=96, then use the pinned bonuses 0 and 10 to predict each adjusted value.