Junior — Middle
Kas `val` tüüpi väärtus on muutumatu pärast selle deklareerimist?
sobes.tech AI
Vastus AI-lt
In Kotlin, the keyword val indicates an immutable reference, meaning that once a variable declared with val is assigned a value, this reference cannot be changed to point to another object. However, this does not mean that the object itself that val points to is immutable. If the object is mutable (for example, MutableList), its internal state can be changed, even though the val reference remains the same.
Example:
val list = mutableListOf(1, 2, 3)
list.add(4) // This is allowed, the contents of the list change
// list = mutableListOf(5, 6) // Error: cannot reassign a `val`
Therefore, val guarantees the immutability of the reference, but not of the object.