Search code examples
kotlinvariablesbackend

Why is it more recommended to use 'val' instead of 'var'?


Recently, I was taking a Kotlin course, and the instructor mentioned that the recommendation is, whenever possible, to use 'val' instead of 'var'. What would be the reason behind this recommendation?

Examplo:

var name: String = "Jannayna"

or

val name: String = "Jannayna"

Solution

  • If you use val (without custom get()), you know the value won’t change, which makes all your code that uses that property or variable easier to reason about because there are less “moving parts” to keep under consideration.

    In Kotlin, a variable or property is either a val or a var instead of like some other languages where a variable is by default mutable and can be restricted with a keyword like final or const. Therefore, when you see var instead of val, you know the writer of that code intentionally made it mutable and weren’t just being lazy by omitting a keyword. So using var communicates that the variable or property is not just mutable, but expected to be mutated at some point.