How to Add Element to List in Kotlin: Simple Guide
In Kotlin, you add an element to a list by using a
MutableList and calling its add() method. Immutable lists created with listOf() cannot be changed, so use mutableListOf() to add elements.Syntax
To add an element to a list in Kotlin, you need a mutable list. The syntax is:
val list = mutableListOf<Type>()- creates a mutable list.list.add(element)- adds the element to the list.
kotlin
val list = mutableListOf<String>()
list.add("Hello")Example
This example shows how to create a mutable list, add elements, and print the list.
kotlin
fun main() {
val fruits = mutableListOf("Apple", "Banana")
fruits.add("Cherry")
println(fruits)
}Output
[Apple, Banana, Cherry]
Common Pitfalls
A common mistake is trying to add elements to an immutable list created with listOf(). This causes a runtime error because immutable lists cannot be changed.
Wrong way:
val list = listOf("A", "B")
list.add("C") // Error: Unresolved reference or UnsupportedOperationExceptionRight way:
val list = mutableListOf("A", "B")
list.add("C") // Works fineQuick Reference
| Operation | Code Example | Description |
|---|---|---|
| Create mutable list | val list = mutableListOf | Creates a list you can change |
| Add element | list.add(element) | Adds element to the list |
| Create immutable list | val list = listOf | Creates a list you cannot change |
| Add element to immutable list | list.add(element) | Causes error, not allowed |
Key Takeaways
Use mutableListOf() to create a list you can add elements to.
Call add() on a mutable list to add new elements.
Immutable lists from listOf() cannot be changed after creation.
Trying to add to an immutable list causes errors.
Always choose the right list type based on whether you need to modify it.