Interview frequency: …
Short answer
val declares a reference that cannot be reassigned (read-only), while var declares a variable that can be modified and reassigned (mutable).
Explanation
In Kotlin it is always preferable to use val to promote immutability and avoid side effects across multiple threads. Note that val prevents re-pointing the reference to another object, but if the object itself is mutable (such as a MutableList) its internal contents can still be modified.
Code example
val name = "Android" // Cannot be reset
// name = "Kotlin" // Compile-time error
var counter = 0
counter += 1 // Allowed
val list = mutableListOf("A", "B")
list.add("C") // Allowed because the object itself is mutableCommon mistakes
- Believing that val means the object's contents are completely unchangeable (deep immutability), like const.
- Using var with no real need to modify the value, which reduces code clarity and raises the chance of bugs.