Kotlin Mutable List
Kotlin Mutable List is a collection of elements which can support modifications to the List. We can add elements to or remove elements from this Mutable List.
In this tutorial, we will go through basic topics of a mutable list like creating a mutable list, adding elements to a mutable list and removing elements from a mutable list.
Create Mutable List
To create a mutable list in Kotlin, call mutableListOf()
function and pass the elements to it.
The syntax of mutableListOf()
function is
fun <T> mutableListOf(vararg elements: T): MutableList<T>
In the following program, we will create a mutable list of integers.
Main.kt
fun main(args: Array<String>) {
val mutableList = mutableListOf(1, 3, 9)
println(mutableList)
}
Output
[1, 3, 9]
Add Element to Mutable List
To add an element to a Mutable List, call add()
function on this mutable list and pass the element. The new element will be added at the end of the list. We can also specify the index, at which the element has to be inserted.
The syntax to use add() function with element is
MutableList.add(element)
The syntax to use add() function with specific index and element is
MutableList.add(index, element)
Examples
In the following program, we will create a mutable list of integers, and add elements to it using add(element)
and add(index, element)
functions.
Main.kt
fun main(args: Array<String>) {
val mutableList = mutableListOf(1, 3, 9)
mutableList.add(16)
mutableList.add(2, 25)
println(mutableList)
}
Output
[1, 3, 25, 9, 16]
Remove Element from Mutable List
To remove an element from a Mutable List, call remove()
function on this mutable list and pass the element. The first occurrence, if any, of this specified element will be removed from this mutable list.
The syntax to use remove() function with element is
MutableList.remove(element)
In the following program, we will create a mutable list of integers, and remove the element 9
from the mutable list using remove(element)
function.
Main.kt
fun main(args: Array<String>) {
val mutableList = mutableListOf(1, 3, 9, 16)
mutableList.remove(9)
println(mutableList)
}
Output
[1, 3, 16]
Conclusion
Concluding this introductory tutorial to Mutable List in Kotlin, we have covered only basic topics like creating, adding an element and removing an element.