Intern
What are the differences between 'val' and 'var' in Kotlin?
sobes.tech AI
Answer from AI
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 variable's lifetime.
Example:
fun main() {
val readOnlyValue = 10 // Assigned the value 10
// readOnlyValue = 20 // Compilation error: Val cannot be reassigned
var mutableValue = 30 // Assigned the value 30
mutableValue = 40 // Reassigned the value 40
println(mutableValue) // Will output 40
}
Using val is preferable when possible, as it increases code safety and often makes the code more predictable.