val vs var
At the café, the shop's name never changes, but the count of cups sold goes up with every order. When you store these in a program, telling Kotlin which is which prevents a whole family of bugs where something changes that never should.
The rule
val is fixed once; var may be reassigned. Start with val.
val shopName = "Pebble Café"
var cupsSold = 0
cupsSold = cupsSold + 1 // fine: var can be reassigned
cupsSold += 2 // also fine, now 3
shopName = "Other Café" // compile error: val cannot be reassignedval(value) is assigned exactly once. After that, the name always refers to the same thing. It is likefinalin Java.var(variable) can be given a new value as often as you like, as long as it has the same type.cupsSold = "three"is an error becausecupsSoldis anInt.
A val can be declared first and assigned later, but only once:
val openingHour: Int
openingHour = 8 // first and only assignmentRead-only is about the name, not the object. A val pointing at a mutable list still lets you change the list:
val orders = mutableListOf("latte")
orders.add("mocha") // allowed: same list, new contents
orders = mutableListOf() // error: that would reassign the valThere is also const val for fixed values known when the program is compiled, such as const val MAX_CUPS = 12. It works only at the top level or inside an object, and only for primitive types like Int and for String.
The shortcut
Write val by default. When the compiler complains "Val cannot be reassigned", ask: does this value really change over time? If yes, switch to var. If no, you have found a bug.
Shop name
It never changes:
val shopName = "Pebble Café".
The trap: thinking val means "the contents can never change". It only freezes which object the name points to.
Drills
Answer fast — trust the rule.
Which line causes a compile error?
var cupsSold = 0 — which assignment is rejected?
val orders = mutableListOf("latte") then orders.add("chai"). What happens?
Where may const val MAX_CUPS = 12 be declared?
Remember
valis assigned once;varcan be reassigned with a value of the same type.- Default to
val; switch tovaronly when a value really changes. valfreezes the name, not the object it points to.
