Junior — Middle
Milline on vahe muutujate deklaratsioonide vahel var ja val Kotlinis?
sobes.tech AI
Vastus AI-lt
In Kotlin, var and val are used to declare variables, but they have a fundamental difference:
var— declares a mutable variable. The value of such a variable can be changed after initialization.val— declares an immutable variable, similar to a constant. Once assigned a value, it cannot be changed.
Example:
var mutableVar = 10
mutableVar = 20 // allowed
val immutableVal = 30
// immutableVal = 40 // compilation error
It is recommended to use val when the value should not change, as it increases code safety and readability.