What Is the Difference Between val and var in Kotlin, and Is val Immutable?
In short: var can be given a new value. val can't. But val only locks the name, not the object behind it. A val list can still grow, and a val property can return a new value each time you read it. That's why Kotlin calls val read-only, not immutable. val stops you from changing the name. It doesn't stop you from changing the thing. Say a search screen shows your recent searches. The state is a…
The key difference between val and var in Kotlin lies in whether the variable's value can be reassigned. Var allows a variable to be reassigned to a new value, while val cannot be reassigned once it's initialized. However, it's important to note that val does not make the object immutable. A val property can still return a new value each time it's read, because it only locks the reference to the object, not the object itself. This is why Kotlin refers to val as read-only, rather than immutable.
The reason val is considered read-only and not immutable is because it locks the reference to an object, not the object itself. This means that while the reference to the object cannot be changed, the object itself can still be modified. For example, a val list can still grow or have new items added to it. This is why Kotlin refers to val as read-only, not immutable.
In the context of Android development, this distinction can be particularly important. For instance, in the provided search screen example, using val for the state could lead to unexpected behavior. The state is defined as a MutableList<String>, which allows items to be added. When a search query is added, the code calls recent.add(query), but because recent is a val, it cannot be reassigned to a new MutableList<String>.
As a result, even though the list changes, the view on the screen does not update. To fix this, the list can be changed to a read-only List<String>, and a new SearchState is created each time a search query is added.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to