Sobes.tech
Junior — Middle

How to insert elements into a List collection in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, the List collection is immutable by default, so you cannot insert elements directly. To insert, you need to use a mutable list, MutableList.

Example of inserting an element into a MutableList:

val list = mutableListOf(1, 2, 3)
list.add(1, 10) // insert the number 10 at index 1
println(list) // [1, 10, 2, 3]

If you have an immutable List, you can create a new list with added elements:

val list = listOf(1, 2, 3)
val newList = list.toMutableList()
newList.add(1, 10)
println(newList) // [1, 10, 2, 3]
How to insert elements into a List collection in… - sobes.tech