0
0
KotlinComparisonBeginner · 3 min read

ListOf vs mutableListOf in Kotlin: Key Differences and Usage

listOf creates an immutable list that cannot be changed after creation, while mutableListOf creates a mutable list that allows adding, removing, or updating elements. Use listOf when you want a fixed list and mutableListOf when you need to modify the list later.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of listOf and mutableListOf in Kotlin.

FeaturelistOfmutableListOf
MutabilityImmutable (read-only)Mutable (can change)
Add elements after creationNoYes
Remove elements after creationNoYes
Update elementsNoYes
Returns typeListMutableList
Use caseFixed data, safetyDynamic data, flexibility
⚖️

Key Differences

The main difference between listOf and mutableListOf lies in mutability. listOf returns an immutable list, meaning once created, you cannot add, remove, or change its elements. This is useful when you want to ensure the list stays constant and avoid accidental changes.

On the other hand, mutableListOf returns a mutable list that supports operations like add(), remove(), and element updates. This makes it suitable for cases where the list content needs to change during program execution.

Both functions create lists with the same element order and allow duplicates, but their mutability affects how you can work with them in your code.

⚖️

Code Comparison

Here is how you create and try to modify a list using listOf. Notice that modification is not allowed.

kotlin
val immutableList = listOf("apple", "banana", "cherry")
println(immutableList)
// The following line would cause a compile error:
// immutableList.add("date")
Output
[apple, banana, cherry]
↔️

mutableListOf Equivalent

Using mutableListOf, you can add and remove elements freely after creation.

kotlin
val mutableList = mutableListOf("apple", "banana", "cherry")
println(mutableList)
mutableList.add("date")
println(mutableList)
mutableList.remove("banana")
println(mutableList)
Output
[apple, banana, cherry] [apple, banana, cherry, date] [apple, cherry, date]
🎯

When to Use Which

Choose listOf when you want a list that should not change after creation, which helps prevent bugs and makes your code safer. It's ideal for fixed data like configuration values or constants.

Choose mutableListOf when you need to add, remove, or update elements dynamically, such as when collecting user input or managing a list that changes over time.

Key Takeaways

listOf creates an immutable list that cannot be changed after creation.
mutableListOf creates a mutable list that supports adding, removing, and updating elements.
Use listOf for fixed data to ensure safety and immutability.
Use mutableListOf when you need a list that changes during program execution.
Both maintain element order and allow duplicates, but differ in mutability.