Foundations
Variables
Values store data that later expressions can reuse.
val
Use `val` for a local value that is assigned once.
Variables
Variables.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val unitPrice = 12
val quantity = 3
val total = unitPrice * quantity
println("unit=" + unitPrice)
println("total=" + total)
}
}
object Main {
def main(args: Array[String]): Unit = {
val unitPrice = 8
val quantity = 3
val total = unitPrice * quantity
println("unit=" + unitPrice)
println("total=" + total)
}
}
object Main {
def main(args: Array[String]): Unit = {
val unitPrice = 20
val quantity = 3
val total = unitPrice * quantity
println("unit=" + unitPrice)
println("total=" + total)
}
}
unitPrice ← 12, quantity ← 3, total ← 36
1object Main {2 def main(args: Array[String]): Unit = {3 val unitPrice→ 12 = 12 //@unitPrice=8, 204 val quantity→ 3 = 35 val total→ 36 = unitPrice12 * quantity367 println("unit=" + unitPrice12)8 println("total=" + total36)9 }10}outputunit=12 total=36
unitPrice ← 8, quantity ← 3, total ← 24
1object Main {2 def main(args: Array[String]): Unit = {3 val unitPrice→ 8 = 84 val quantity→ 3 = 35 val total→ 24 = unitPrice8 * quantity367 println("unit=" + unitPrice8)8 println("total=" + total24)9 }10}outputunit=8 total=24
unitPrice ← 20, quantity ← 3, total ← 60
1object Main {2 def main(args: Array[String]): Unit = {3 val unitPrice→ 20 = 204 val quantity→ 3 = 35 val total→ 60 = unitPrice20 * quantity367 println("unit=" + unitPrice20)8 println("total=" + total60)9 }10}outputunit=20 total=60
What Happens
unitPricestarts at12.quantitystarts at3.total = unitPrice * quantitymultiplies12 * 3.totalbecomes36.- The program prints
unit=12andtotal=36.
Follow the Values
| unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |
Exercise: Variables.scala
Reproduce unit=12 and total=36, then use the pinned unitPrice values 8 and 20 to predict each total.