This confusion about val
, List
, and immutability vs. read-only comes up so much. I wonder if it would be worth adding a section to the docs that tries to explain this with diagrams or something. Maybe this is all already there somewhere but it would be nice to have once spot we could point people to when they get it wrong.
Trying to summarize what could be explained in that section:
A val
variable’s value is usually a reference to an object. The value of the variable cannot be changed to refer to a different object. However, the object to which the val
variable refers can modified unless the object itself is immutable.
A variable of type List
is a read-only view to a mutable object whether the variable is declared with var
or val
. It is possible to modify the object referenced by that variable by using another variable of type MutableList
referencing the same object.
fun main(args: Array<String>) {
val c = mutableListOf("a", "b")
val d: List<*> = c as List<*>
println("d = $d")
c.removeAt(0)
println("d = $d")
}