Part 02 / Topic 1 of 8
val and var: read-only versus reassignable
A val is a reference you set once; a var is one you can reassign. Kotlin pushes you toward
val by default — most values in a well-written Kotlin program never change after they're set,
and the compiler enforces that rather than just hoping for it.
fun main() {
val restaurant = "Saffron Kitchen, Koramangala"
var runningTotal = 0.0
runningTotal += 320.0 // Masala Dosa
runningTotal += 180.0 // Filter Coffee x2
runningTotal += 450.0 // Paneer Butter Masala
println("Restaurant: $restaurant")
println("Running total so far: $runningTotal")
}
$ kotlinc 01_val_and_var.kt -include-runtime -d 01.jar
$ java -jar 01.jar
Restaurant: Saffron Kitchen, Koramangala
Running total so far: 950.0
restaurant never changes, so it's a val; runningTotal grows as items get added, so it's a
var. Try reassigning the val instead, and kotlinc refuses to compile it at all, not just at
run time:
fun main() {
val restaurant = "Saffron Kitchen"
restaurant = "Spice Garden"
println(restaurant)
}
$ kotlinc ValError.kt -d out
ValError.kt:3:5: error: 'val' cannot be reassigned.
restaurant = "Spice Garden"
^^^^^^^^^^
This is a compile-time guarantee, not a convention you have to remember to follow — if a value
is declared val, nothing later in the file can quietly change it under you.
Full program: examples/01_val_and_var.kt.
Done here? The practice set for Part 2 — including the solutions — is on the part page.