Variables store values that expressions can reuse.

val Use `val` for a read-only local value.

Variables

unitPrice
Variables.kt
Replay: real traced execution (multi-file project)
fun main() {
    val unitPrice = 12
    val quantity = 3
    val total = unitPrice * quantity

    println("unit=$unitPrice")
    println("total=$total")
}
fun main() {
    val unitPrice = 8
    val quantity = 3
    val total = unitPrice * quantity

    println("unit=$unitPrice")
    println("total=$total")
}
fun main() {
    val unitPrice = 20
    val quantity = 3
    val total = unitPrice * quantity

    println("unit=$unitPrice")
    println("total=$total")
}
  1. unitPrice ← 12, quantity ← 3, total ← 36

    1fun main() {2    val unitPrice→ 12 = 12 //@unitPrice=8, 203    val quantity→ 3 = 34    val total→ 36 = unitPrice12 * quantity356    println("unit=$unitPrice12")7    println("total=$total36")8}
    outputunit=12
    total=36
  1. unitPrice ← 8, quantity ← 3, total ← 24

    1fun main() {2    val unitPrice→ 8 = 83    val quantity→ 3 = 34    val total→ 24 = unitPrice8 * quantity356    println("unit=$unitPrice8")7    println("total=$total24")8}
    outputunit=8
    total=24
  1. unitPrice ← 20, quantity ← 3, total ← 60

    1fun main() {2    val unitPrice→ 20 = 203    val quantity→ 3 = 34    val total→ 60 = unitPrice20 * quantity356    println("unit=$unitPrice20")7    println("total=$total60")8}
    outputunit=20
    total=60

Follow the Total

  1. unitPrice starts at 12.
  2. quantity starts at 3.
  3. total = unitPrice * quantity multiplies 12 * 3.
  4. total becomes 36.
  5. The program prints unit=12 and total=36. | unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |

Exercise: Variables.kt

Reproduce unit=12 and total=36, then try unitPrice 8 and 20 and predict each total before running it.