Search code examples
kotlinmutable

How can you change the value of a mutable list/map/array when its defined as a val type in Kotlin


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?


Solution

  • 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")