Kotlin Mutable Lists
A mutable list is a list that can change after it is built. Adding and removing values change the list itself.
Before and after an add
The first print shows the list before the add. The second print shows one more value at the end.
fun main() {
val names = mutableListOf("Ana", "Bo")
println(names)
names.add("Cy")
println(names)
}A value dropped by index
removeAt uses index 0. The first value is gone in the printed list.
fun main() {
val names = mutableListOf("Ana", "Bo", "Cy")
names.removeAt(0)
println(names)
}One value replaced by index
The code sets index 1 to a new name. The printed list shows that one change.
fun main() {
val names = mutableListOf("Ana", "Bo", "Cy")
names[1] = "Bea"
println(names)
}Example
fun main() {
val names = mutableListOf("Ana", "Bo")
names.add("Cy")
names.removeAt(0)
names[0] = "Bea"
println(names)
println(names.size)
}Key points
- mutableListOf: the call that builds a list that can change.
- Use .add to place a new value at the end of the list.
- Use .removeAt to drop the value at one index.
- Use an index in square brackets to replace one value.
- The val holding the list keeps pointing at the same list.
In this example, the list starts with Ana and Bo. Adding Cy makes three values, and removing index 0 drops Ana. Setting index 0 replaces Bo with Bea, so the list prints Bea and Cy with size 2.
Note
Adding a value changes the list itself, not the val that holds it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does names.add("Cy") do to a mutable list?