To append an element to a list in Kotlin, you can use the add
method for a mutable list or the plus
method for an immutable list.
In this example,
numbers
with initial integer values.add
method of the mutable list numbers
to append a new integer to the list.add
method modifies the original list by adding the new element at the end.fun main(args: Array<String>) {
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
println("Updated list: $numbers")
}
Updated list: [1, 2, 3, 4, 5]
In this example,
numbers
with initial integer values.plus
method to create a new list by appending a new integer to the original list.plus
method returns a new list with the original elements and the new element added at the end.fun main(args: Array<String>) {
val numbers = listOf(1, 2, 3, 4)
val updatedNumbers = numbers + 5
println("Updated list: $updatedNumbers")
}
Updated list: [1, 2, 3, 4, 5]
In this tutorial, we learned How to Append an Element to a List in Kotlin language with well detailed examples.