In which case we have to use val instead of var ? I know val is when we know the value is not going to change. But I am under the impression that var is good for all case. Is that true ? In others words : is it a problem to only use var ?
Asked
Active
Viewed 512 times
-1
-
1Does this answer your question? [Val and Var in Kotlin](https://stackoverflow.com/questions/44200075/val-and-var-in-kotlin) – MehranB Dec 25 '20 at 17:06
-
Not exactly. I wonder if we can code only using var without bad consequences. I am not able to see the real utility of val. – jujuf1 Dec 25 '20 at 17:10
-
2If you want an assigned variable to stay a constant value and not be inadvertently changed during it's lifetime, use val. Code has a lifetime that may extend beyond just you as the maintainer. If you use var for such a case, it is ambiguous what the intent of the value's use is supposed to be. – Michael Krause Dec 25 '20 at 17:10
-
1`val` is always preferable if the value doesn't need to change because fewer opportunities for mutability makes the overall design simpler and easier to maintain. And for public properties, `var` implies that something useful will happen when it changes. – Tenfour04 Dec 25 '20 at 20:19
1 Answers
1
Imagine you have a very long function that declares some val
at the beginning. You now immediately know that its value will not change anywhere in that long body of code. If it was a var
then you'd have to read the whole code to try and understand what is stored in that variable at any given point in the function. So the purpose of val
is to simplify the understanding of complex code by making it clear that this value will absolutely never change and you do not need to read the rest of the code to be sure of that.

zOqvxf
- 1,469
- 15
- 18
-
is this the only advantage? we should use var (or java final) until we need to change its value and THEN go back and change it to var? – White_King Sep 16 '21 at 21:53