Junior — Middle
Is a val type value immutable after its declaration?
sobes.tech AI
Answer from AI
In Kotlin, the keyword val denotes an immutable reference, meaning that after assigning a value to a variable declared with val, you cannot change this reference to point to another object. However, this does not mean that the object itself, which val refers to, is immutable. If the object is mutable (for example, MutableList), its internal state can be changed, even though the val reference itself cannot be reassigned.
Example:
val list = mutableListOf(1, 2, 3)
list.add(4) // This is allowed, the contents of the list are changed
// list = mutableListOf(5, 6) // Error: cannot reassign a `val`
Thus, val guarantees the immutability of the reference, but not the immutability of the object.