Question

How to Initialize an Empty MutableList in Kotlin

Question

I want to initialize a Kotlin MutableList as an empty list.

I found a workaround like this, but it feels more complicated than necessary:

var pusta: List<Kolory> = emptyList()
var cos: MutableList<Kolory> = pusta.toArrayList()

What is the simplest and correct way to create an empty MutableList<Kolory> in Kotlin?

Short Answer

By the end of this page, you will understand how to create an empty MutableList in Kotlin, how it differs from List, and which standard functions like mutableListOf() and arrayListOf() are most commonly used.

Concept

In Kotlin, List and MutableList are different interfaces.

  • List<T> is read-only: you can access items, but you cannot add or remove them through that reference.
  • MutableList<T> is modifiable: you can add, remove, and update elements.

If you need an empty mutable list, Kotlin provides built-in factory functions for that. The most common one is:

val items = mutableListOf<Kolory>()

This creates an empty list that you can change later.

Why this matters:

  • It is shorter and clearer than creating a read-only list first and then converting it.
  • It communicates your intent directly: you want a mutable collection.
  • It uses Kotlin's standard collection APIs, which are common in real codebases.

Your original approach creates an empty List first and then converts it to a mutable implementation. That works, but it is unnecessary when Kotlin already gives you a direct way to create an empty MutableList.

Mental Model

Think of List and MutableList like two kinds of notebooks:

  • A List is a read-only notebook. You can read the pages, but you are not allowed to write in it.
  • A MutableList is a writable notebook. You can add notes, erase lines, and change entries.

If you know from the start that you need to write into the notebook, it makes more sense to create a writable one immediately instead of creating a read-only one and copying it.

Take Quiz

Syntax and Examples

The simplest way to create an empty mutable list in Kotlin is:

val colors = mutableListOf<Kolory>()

You can then modify it:

colors.add(Kolory.RED)
colors.add(Kolory.BLUE)

Another valid option

If you specifically want an ArrayList, you can write:

val colors = arrayListOf<Kolory>()

This also creates an empty mutable list.

Example with a simple type

val names = mutableListOf<String>()
names.add("Alice")
names.add("Bob")
println(names)

Output:

[Alice, Bob]

Why val is usually enough

Even though the list is mutable, the variable itself often does not need to be reassigned:

val numbers = mutableListOf<Int>()
numbers.add(10)
numbers.add(20)

val means the variable cannot point to a different list later, but the list contents can still change. This is usually preferred because it reduces accidental reassignment.

Step by Step Execution

Consider this code:

val numbers = mutableListOf<Int>()
numbers.add(5)
numbers.add(8)
numbers.remove(5)
println(numbers)

Step by step:

  1. mutableListOf<Int>()

    • Creates a new empty mutable list of integers.
    • At this point: []
  2. numbers.add(5)

    • Adds 5 to the list.
    • Now the list is: [5]
  3. numbers.add(8)

    • Adds 8 to the end.
    • Now the list is: [5, 8]
  4. numbers.remove(5)

    • Removes the element 5.
    • Now the list is: [8]
  5. println(numbers)

    • Prints the current contents.

Output:

[8]

This shows that the list starts empty and can be updated over time.

Real World Use Cases

Empty mutable lists are common when your program builds data gradually.

Collecting results in a loop

val validEmails = mutableListOf<String>()

for (email in emails) {
    if (email.contains("@")) {
        validEmails.add(email)
    }
}

Building API response data

val errors = mutableListOf<String>()

if (username.isBlank()) errors.add("Username is required")
if (password.length < 8) errors.add("Password must be at least 8 characters")

Preparing UI items

val menuItems = mutableListOf<String>()
menuItems.add("Home")
menuItems.add("Profile")
menuItems.add("Settings")

Reading and transforming data

val positiveNumbers = mutableListOf<Int>()
for (n in inputNumbers) {
    if (n > 0) positiveNumbers.add(n)
}

In all of these examples, the list starts empty and grows as the program processes information.

Take Quiz

Real Codebase Usage

In real Kotlin projects, developers often use mutableListOf() when they need to build a collection step by step.

Common pattern: accumulate values

val messages = mutableListOf<String>()

if (user == null) {
    messages.add("User not found")
}

if (messages.isNotEmpty()) {
    return messages
}

Validation and error collection

fun validateUser(name: String, age: Int): List<String> {
    val errors = mutableListOf<String>()

    if (name.isBlank()) errors.add("Name cannot be blank")
    if (age < 0) errors.add("Age cannot be negative")

    return errors
}

Building a result list before returning read-only data

A common practice is to use a mutable list internally, then return it as List:

fun loadVisibleItems(allItems: List<String>): List<String> {
    val result = mutableListOf<String>()

    for (item in allItems) {
        if (!item.startsWith("_")) {
            result.add(item)
        }
    }

    return result
}

This keeps implementation flexible while exposing a safer read-only type.

Prefer intention-revealing code

Use mutableListOf() when you want a mutable list. Use emptyList() when you want an empty read-only list.

That small distinction makes code easier to understand and maintain.

Common Mistakes

1. Using emptyList() when you need mutation

Broken example:

val items: List<String> = emptyList()
items.add("hello")

Problem:

  • List does not allow add.
  • This will not compile.

Fix:

val items = mutableListOf<String>()
items.add("hello")

2. Converting unnecessarily

Less clear approach:

val items: List<String> = emptyList()
val mutableItems: MutableList<String> = items.toMutableList()

Problem:

  • It works, but it is extra work for something Kotlin can do directly.

Better:

val mutableItems = mutableListOf<String>()

3. Confusing val with immutability

Beginners often think this is wrong:

val items = mutableListOf<String>()
items.add("A")

But this is valid.

  • val means the variable reference cannot be reassigned.
  • It does not mean the object itself is immutable.

4. Using var when not needed

Not wrong, but often unnecessary:

var items = mutableListOf<String>()

Prefer:

val items = mutableListOf<String>()

Use var only if you plan to replace the whole list with another one.

5. Assuming MutableList always means ArrayList

MutableList is an interface. The actual implementation may vary.

If you only need list operations, prefer:

val items = mutableListOf<String>()

Only choose a specific implementation like ArrayList if you have a real reason.

Comparisons

OptionType createdMutable?Common use
emptyList<T>()List<T>NoEmpty read-only list
listOf<T>()List<T>NoRead-only list with items
mutableListOf<T>()MutableList<T>YesGeneral-purpose mutable list
arrayListOf<T>()ArrayList<T>YesWhen you specifically want ArrayList
list.toMutableList()MutableList<T>YesCopy an existing list into a mutable one

mutableListOf() vs arrayListOf()

FeaturemutableListOf()arrayListOf()
Recommended for general useYesSometimes
Returns mutable listYesYes
Exposes specific implementationNoYes
Best whenYou just need a mutable listYou explicitly want ArrayList

In most beginner and everyday Kotlin code, mutableListOf() is the best choice.

Take Quiz

Cheat Sheet

// Empty read-only list
val a = emptyList<String>()

// Empty mutable list
val b = mutableListOf<String>()

// Empty ArrayList
val c = arrayListOf<String>()

// Convert existing list to mutable
val d = listOf("a", "b").toMutableList()

Quick rules

  • Use emptyList<T>() for an empty read-only list.
  • Use mutableListOf<T>() for an empty mutable list.
  • Use val for mutable lists unless you need to reassign the variable.
  • Use toMutableList() when you already have another list and want a mutable copy.

Best answer to the original question

val cos = mutableListOf<Kolory>()

If you need var

var cos = mutableListOf<Kolory>()

Edge case

If type inference cannot determine the type, specify it explicitly:

val items: MutableList<Kolory> = mutableListOf()

FAQ

How do I create an empty MutableList in Kotlin?

Use:

val items = mutableListOf<Type>()

What is the difference between List and MutableList in Kotlin?

List is read-only through its interface. MutableList allows adding, removing, and changing elements.

Should I use mutableListOf() or arrayListOf()?

Usually use mutableListOf(). Choose arrayListOf() only when you specifically need an ArrayList.

Can I use val with a MutableList?

Yes. val prevents reassignment of the variable, but you can still modify the list contents.

Why does emptyList() not work for adding items?

Because it returns a List, which is read-only through that type.

How do I convert a List to a MutableList in Kotlin?

Use:

val mutable = existingList.toMutableList()

Is mutableListOf() the idiomatic Kotlin way?

Yes. It is the standard and most readable way to create a mutable list.

Take Quiz

Mini Project

Description

Create a small Kotlin program that builds a shopping list from scratch using an empty MutableList. This demonstrates the exact use case where a list starts empty and is populated as the program runs.

Goal

Build and modify an empty MutableList<String> by adding, removing, and printing shopping items.

Requirements

  1. Start with an empty MutableList<String>.
  2. Add at least three shopping items.
  3. Remove one item from the list.
  4. Print the final list.
  5. Use mutableListOf() to create the list.
Take Quiz

Keep learning

Related questions

View more