Kotlin List – Remove all Elements
We can modify the contents of a List only if the list is mutable.
To remove all elements from a Mutable List in Kotlin, call clear()
function on this list object.
The syntax of MutableList.clear() function is
</>
Copy
MutableList.clear()
Example
In the following program, we will create a mutable list with some elements in it. We shall then clear the contents of this list using clear() function.
Main.kt
</>
Copy
fun main(args: Array<String>) {
val mutableList = mutableListOf(1, 3, 9, 16, 25)
println("List before clearing : " + mutableList)
mutableList.clear()
println("List after clearing : " + mutableList)
}
Output
List before clearing : [1, 3, 9, 16, 25]
List after clearing : []
Conclusion
In this Kotlin Tutorial, we learned how to remove all the elements in a mutable list in Kotlin, using clear() function, with the help of example programs.