Add elements to a list in Kotlin
This article explores different ways to add elements to a list in Kotlin.
1. Using add() function
The standard and recommended approach to add the specified element at the end of a mutable list is with the add() function.
|
1 2 3 4 5 6 |
fun main() { val list: MutableList<Int> = mutableListOf(1, 2, 3) // or, use `arrayListOf` list.add(4) println(list) // [1, 2, 3, 4] } |
2. Using += operator
The add() function is not available for an immutable list. In the case of immutable lists, you can create a new list with the additional element.
|
1 2 3 4 5 6 |
fun main() { var list = listOf(1, 2, 3) // var, not val list += 4 println(list) // [1, 2, 3, 4] } |
3. Using addAll() function
If you need to add multiple elements to a mutable list, you can use the addAll() function.
|
1 2 3 4 5 6 |
fun main() { val list: MutableList<Int> = arrayListOf(1, 2, 3) list.addAll(listOf(4, 5)) println(list) // [1, 2, 3, 4, 5] } |
That’s all about adding elements to a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)