0
0
KotlinHow-ToBeginner · 3 min read

How to Create MutableList in Kotlin: Syntax and Examples

In Kotlin, you create a mutable list using mutableListOf(). This function returns a MutableList that you can change by adding, removing, or updating elements.
📐

Syntax

The basic syntax to create a mutable list in Kotlin is using the mutableListOf() function. You can specify the elements inside the parentheses separated by commas.

  • mutableListOf(): Creates an empty mutable list.
  • mutableListOf(element1, element2, ...): Creates a mutable list with initial elements.
  • The returned list supports adding, removing, and updating elements.
kotlin
val emptyList = mutableListOf<String>()
val numbers = mutableListOf(1, 2, 3, 4)
💻

Example

This example shows how to create a mutable list, add new elements, remove an element, and update an element. It prints the list after each change to show how it updates.

kotlin
fun main() {
    val fruits = mutableListOf("Apple", "Banana", "Cherry")
    println(fruits) // Initial list

    fruits.add("Date")
    println(fruits) // After adding "Date"

    fruits.remove("Banana")
    println(fruits) // After removing "Banana"

    fruits[0] = "Apricot"
    println(fruits) // After updating first element
}
Output
[Apple, Banana, Cherry] [Apple, Banana, Cherry, Date] [Apple, Cherry, Date] [Apricot, Cherry, Date]
⚠️

Common Pitfalls

One common mistake is trying to modify a list created with listOf(), which is read-only and does not allow changes. Always use mutableListOf() if you want to change the list.

Another pitfall is assuming the list is thread-safe; MutableList is not synchronized, so use proper synchronization if accessed from multiple threads.

kotlin
fun main() {
    val readOnlyList = listOf(1, 2, 3)
    // readOnlyList.add(4) // This will cause a compile error

    val mutableList = mutableListOf(1, 2, 3)
    mutableList.add(4) // This works fine
    println(mutableList)
}
Output
[1, 2, 3, 4]
📊

Quick Reference

  • Create empty mutable list: mutableListOf<Type>()
  • Create with elements: mutableListOf(element1, element2)
  • Add element: list.add(element)
  • Remove element: list.remove(element)
  • Update element: list[index] = newValue

Key Takeaways

Use mutableListOf() to create a list you can change in Kotlin.
MutableList allows adding, removing, and updating elements after creation.
Do not confuse mutableListOf() with listOf(), which is read-only.
MutableList is not thread-safe by default; synchronize if needed.
Access elements by index to update them directly.