Intern
Millised on erinevused 'val' ja 'var' vahel Kotlinis?
sobes.tech AI
Vastus AI-lt
val declares an immutable (read-only) reference. After assigning a value to it, you cannot reassign another value.
var declares a mutable reference. Its value can be changed during the lifetime of the variable.
Example:
fun main() {
val readOnlyValue = 10 // Assigned value 10
// readOnlyValue = 20 // Compilation error: Val cannot be reassigned
var mutableValue = 30 // Assigned value 30
mutableValue = 40 // Reassigned value 40
println(mutableValue) // Will print 40
}
Using val is preferable when possible, as it increases code safety and often makes it more predictable.