Kotlin List – Remove Element at Index

We can modify the contents of a List only if the list is mutable.

To remove an element from a Mutable List at given index in Kotlin, call removeAt() function on this list object and pass the index of the element, that we would like to remove, as argument.

The syntax of removeAt() function is

</>
Copy
MutableList.removeAt(index)

Examples

In the following program, we will create a mutable list with some elements in it. We shall then remove the element at index 3 from this list using removeAt() function.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 25)
    println("List before removing : " + mutableList)
    mutableList.removeAt(3)
    println("List after  removing : " + mutableList)
}

Output

List before removing : [1, 4, 9, 16, 25]
List after  removing : [1, 4, 9, 25]

If the specified index is out of bounds for this list object, then removeAt() throws java.lang.IndexOutOfBoundsException.

In the following program, we will try to remove the element at index 7, while the size of this list is 5.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val mutableList: MutableList<Int> = mutableListOf(1, 4, 9, 16, 25)
    println("List before removing : " + mutableList)
    mutableList.removeAt(7)
    println("List after  removing : " + mutableList)
}

Output

List before removing : [1, 4, 9, 16, 25]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 7 out of bounds for length 5
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
	at java.base/java.util.Objects.checkIndex(Objects.java:372)
	at java.base/java.util.ArrayList.remove(ArrayList.java:536)
	at MainKt.main(Main.kt:4)

Conclusion

In this Kotlin Tutorial, we learned how to remove an element at specific index from a mutable list in Kotlin, using removeAt() function, with the help of example programs.