I'm new to Kotlin and I've been reading a lot about how val
is read-only and var
is mutable. That's fine i get it. But what's confusing is when you create a mutable lsit/map/array and you've assigned it as a val
, how is it allowed to be mutable? Doesn't that change the read-only aspect of val
properties/variables/objects?
class MyObject {
val a = mutableListOf<String>()
}
means that the field for a
is final, and there is no setter for a
.
You thus can't do
myObject.a = anotherList
It says nothing about the mutability of the list itself. Since the list is mutable, you can do
myObject.a.add("foo")