'Why using val instead of var in Kotlin? [duplicate]
I have seen some tutorials that recommend using val instead of var in Kotlin. I beleive val is like constant in Java right? Then how can we change its value if it is recommended to use it instead of var?
Update: for example: why would I want to declare class members (variables or fields) using val rather than var? whereas in Java it is just something like:
private int variableName;
Solution 1:[1]
val is like a final variable in java. Use it if you wont change the value. val is immutable.
var is a normal variable that changes it's value. var is mutable.
For more information on this topic https://medium.com/techmacademy/kotlin-101-val-vs-var-behind-the-scenes-65d96c6608bf
Solution 2:[2]
I beleive
val
is like constant in Java right?
If you mean final
, then yes in the sense that the value can't be changed. See here:
Variables
Read-only local variables are defined using the keyword
val
. They can be assigned a value only once....
Variables that can be reassigned use the
var
keyword.
and here:
Declaring properties
Properties in Kotlin classes can be declared either as mutable, using the
var
keyword, or as read-only, using theval
keyword.
Continuing with your question:
Then how can we change it's value if it is recommended to use it instead of
var
?
You can't, that's the point. It says to the programmer reading it (and the compiler and JVM) that the value won't be changed.
I understand that functional programming is popular in Kotlin. So you may be seeing people saying to use val
as part of doing functional programming in general (which prefers creating new, updated data objects to modifying the state of a data object).
Solution 3:[3]
The reason Kotlin recommends val
is that Android, which mainly uses Kotlin, adopts the Clean architecture, and each layer maintains multiple states to ensure that the states do not change (integrity) when exchanging data with each other.
If the value must change logically, as mentioned above, use var
else use val ooo : MutableObject
for an object that is not of a general type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 |