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?
            Asked
            
        
        
            Active
            
        
            Viewed 233 times
        
    0
            
            
        
        Asad Nawaz
        
- 355
 - 1
 - 3
 - 14
 
- 
                    You may want to see: https://stackoverflow.com/questions/44200075/val-and-var-in-kotlin – mrossini Nov 30 '19 at 18:58
 - 
                    @mrossini I did but I felt that didn't help me understand properly – Asad Nawaz Nov 30 '19 at 18:59
 - 
                    1The `val` prevents reassigning, but it doesn't prevent modification. For example, by writing `val list: MutableList
= mutableListOf()`, you say that `list` will always contain the same list, which still can be modified. – IlyaMuravjov Nov 30 '19 at 19:08 
1 Answers
2
            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")
        JB Nizet
        
- 678,734
 - 91
 - 1,224
 - 1,255
 
- 
                    1This makes it seems like it was so simple to begin with i don't know why I didn't get it! Thanks! – Asad Nawaz Nov 30 '19 at 19:38