To insert an element at a specific index in a list in Kotlin, you can use the add
method or addAt
function.
In this example,
numbers
with initial integer values.add
method to insert a new element at the desired index.add
method shifts the existing elements to the right to make space for the new element.fun main() {
val numbers = mutableListOf(1, 2, 3, 4, 5)
numbers.add(2, 10)
println("Updated list: $numbers")
}
Updated list: [1, 2, 10, 3, 4, 5]
In this example,
addAt
on the MutableList
class to insert an element at a specific index.addAt
function, we use the add
method to insert the element at the specified index.addAt
function to insert an element at the desired index in the list.fun main() {
val numbers = mutableListOf(1, 2, 3, 4, 5)
numbers.addAt(2, 10)
println("Updated list: $numbers")
}
fun <T> MutableList<T>.addAt(index: Int, element: T) {
add(index, element)
}
Updated list: [1, 2, 10, 3, 4, 5]
In this tutorial, we learned How to Insert an Element at Specific Index in a List in Kotlin language with well detailed examples.