Kotlin List – Add Element

We can add element to a Mutable List only. An usual List is immutable. So, if we would like to add an element to given list, the list has to be a mutable list, otherwise, we may need to convert it to a mutable list and then add the element.

To add an element to a Mutable List in Kotlin, we can use add(element), or add(index, element) functions.

add(element) adds element to the end of this Mutable List.

add(index, element) adds element to this Mutable List at the given index.

Examples

In the following program, we will create a Mutable List with some integers, and then add some elements to it, using add(element) function.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val mutableList = mutableListOf(1, 3, 9, 16)
    mutableList.add(25)
    mutableList.add(36)
    mutableList.add(49)
    println(mutableList)
}

Output

[1, 3, 9, 16, 25, 36, 49]

Now, let us use add(index, element) function and add an element 88 at index 2.

Main.kt

</>
Copy
fun main(args: Array<String>) {
    val mutableList = mutableListOf(1, 3, 9, 16, 25)
    mutableList.add(2, 88)
    println(mutableList)
}

Output

[1, 3, 88, 9, 16, 25]

The original elements in the mutable list, from index=2, are shifted right.

Conclusion

In this Kotlin Tutorial, we learned how to add an element to a mutable list in Kotlin, using add() function, with the help of example programs.