Programming
kotlin
Updated Sun, 04 Sep 2022 20:31:50 GMT

Why can I instantiate a MutableList as a val in Kotlin (and also add elements to it)?


I'm just in the very early stages of learning Kotlin so I played a video that shows many of the common Kotlin idioms: Kotlin tutorial

Just at the 1:03:10 point in the video, the presenter discusses mutable and immutable collections. As you can see in the video, he creates a MutableList with the var keyword and an immutable List with the val keyword. I was curious to see what error would occur if I tried to use val with a MutableList; I assumed that would not be permissible and that IDEA would display a message to that effect but it gave me no error message. Then I added an element to the MutableList and that didn't cause an error either! When I displayed the last element of the MutableList, it displayed the element that I'd added so it not only failed to give me an error, it successfully added an element to something I thought was immutable.

Why does my code work? I can't believe a total Kotlin beginner like me found a fundamental bug in Kotlin so there must be something else going on. Can someone explain?

Here's my code:

val list3: MutableList<Int> = mutableListOf(6,7,8) 
list3.add(5)
println("list3 last item: ${list3.last()}")

The println() statement displays:

list3 last item: 5



Solution

val only means that the variable itself cannot be re-assigned. It does not say anything about the object in that variable being mutable or not.

You would get an error if you tried to do

 val list3: MutableList<Int> = mutableListOf(6,7,8)
 list3 = mutableListOf(1,2,3)   // cannot re-assign to val






External Links

External links referenced by this document: