val vs var
A val is a read-only reference that is assigned once, while a var can be reassigned; prefer val and switch to var only when the value truly has to change.
Compare rebinding a variable with changing the object a val refers to.
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.