Explanation with a complex object
// lets define a data class
data class Color(var name : String)
// lets define all 3 - array, list and mutableList for this Color object
val array = arrayOf(Color("Red"))
val list = listOf(Color("Red"))
val mutableList = mutableListOf(Color("Red"))
- Methods on array
array.add(Color("Green")) // Not Possible - cannot change size
array[0] = Color("Green") // Possible - array object can be changed
array[0].name = "Green" // Possible - object modification allowed by its class
- Methods on list
list.add(Color("Green")) // Not Possible - cannot change size
list[0] = Color("Green") // Not Possible - list object cannot be changed
list[0].name = "Green" // Possible - object modification allowed by its class
- Methods on mutableList
mutableList.add(Color("Green")) // Possible - can change size
mutableList[0] = Color("Green") // Possible - can change object
mutableList[0].name = "Green" // Possible - object modification allowed by its class
Conclusions :
- arrays and list have fixed size, so you cannot add or remove elements
- list cannot be modified, which means you cannot change the object it is holding
- array can be modified, which means you can change the object it is holding
- mutableList can do anything, change size or its objects
NOTE : This doesn't specify anything about the mutability of the object themselves. i.e. if the data class has some property as mutable (var), its property can be modified.
Array
? Only it's elements - the same in theList
. The size ofList
is also fixed. β Unconnected