0
0
KotlinHow-ToBeginner · 3 min read

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 UnsupportedOperationException

Right way:

val list = mutableListOf("A", "B")
list.add("C")  // Works fine
📊

Quick Reference

OperationCode ExampleDescription
Create mutable listval list = mutableListOf()Creates a list you can change
Add elementlist.add(element)Adds element to the list
Create immutable listval list = listOf()Creates a list you cannot change
Add element to immutable listlist.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.