Foundations
Variables
Variables store values that expressions can reuse.
val
Use `val` for a read-only local value.
Variables
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")
}
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
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
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
unitPricestarts at12.quantitystarts at3.total = unitPrice * quantitymultiplies12 * 3.totalbecomes36.- The program prints
unit=12andtotal=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.