Kotlin Arrays & Collections
Estimated reading: 3 minutes 29 views

📋 Kotlin – Lists (Mutable & Immutable): Ordered Collection Guide

🧲 Introduction – Why Learn Kotlin Lists?

Lists are the most commonly used collection type in Kotlin, allowing you to store ordered elements that can include duplicates. Kotlin provides both immutable lists (listOf) and mutable lists (mutableListOf) to balance read-only safety with flexible data handling.

🎯 In this guide, you’ll learn:

  • What Lists are and how they differ from arrays
  • The difference between mutable and immutable Lists
  • How to access, update, and iterate over list items
  • Useful functions like filter(), map(), add(), and remove()

📚 What Is a List in Kotlin?

A List is an ordered collection of elements accessed by index. Kotlin’s List interface supports:

  • Duplicate values
  • Positional access
  • Iteration using loops or lambdas

🛡️ Immutable Lists – listOf()

Immutable lists cannot be modified after creation.

val names = listOf("Alice", "Bob", "Charlie")

println(names[0])         // Alice
println(names.size)       // 3
println("Bob" in names)   // true

✔️ Safer for APIs, configs, or read-only data.


🛠️ Mutable Lists – mutableListOf()

Mutable lists can be updated—elements can be added, removed, or changed.

val fruits = mutableListOf("Apple", "Banana")
fruits.add("Cherry")
fruits.remove("Banana")
fruits[0] = "Mango"

println(fruits)  // [Mango, Cherry]

✔️ Ideal for dynamic data like form inputs or user lists.


🔁 Iterating Over Lists

🔹 Using for loop:

for (fruit in fruits) {
    println(fruit)
}

🔹 Using indices:

for (i in fruits.indices) {
    println("Index $i: ${fruits[i]}")
}

🔹 Using forEach lambda:

fruits.forEach { println("Fruit: $it") }

🧪 Useful List Operations

OperationExampleDescription
add()fruits.add("Lemon")Adds an element
remove()fruits.remove("Apple")Removes an element
indexOf()fruits.indexOf("Mango")Finds index
contains() / in"Apple" in fruitsChecks for presence
first(), last()fruits.first()Gets first or last item
sorted()fruits.sorted()Returns sorted list
filter()fruits.filter { it.startsWith("A") }Filters elements by condition
map()fruits.map { it.uppercase() }Transforms elements

🧬 Convert Between Mutable and Immutable

val immutableList = listOf("X", "Y")
val mutable = immutableList.toMutableList()
mutable.add("Z")

val backToImmutable = mutable.toList()

✅ Conversion is easy and helps mix safety with flexibility.


🔐 Immutable vs Mutable – Side-by-Side

FeaturelistOf() (Immutable)mutableListOf() (Mutable)
Can add/remove❌ No✅ Yes
Thread-safe✅ More predictable❌ Must be synchronized
Ideal forConfigs, constantsForm data, dynamic inputs
Conversion possible✔️ Yes using toMutableList()✔️ Yes using toList()

🚫 Common Mistakes

❌ Mistake✅ Fix
Trying to add/remove in listOf()Use mutableListOf() for modifications
Accessing out-of-bounds indexAlways check .size before indexing
Mixing immutable with mutable logicBe intentional—convert explicitly

✅ Best Practices for Kotlin Lists

TipWhy It Helps
Use listOf() when modification is not neededSafer, cleaner, and more predictable
Use forEach with lambdasCleaner than classic loop for simple iterations
Avoid direct indexing unless necessaryPrefer safe calls or iteration
Use filter(), map() over manual loopsMore readable and expressive

📌 Summary – Recap & Next Steps

Kotlin’s Lists are powerful tools for ordered data handling. Use listOf() when the list should remain unchanged and mutableListOf() for dynamic collections. Take advantage of Kotlin’s expressive collection functions to write clean and efficient list logic.

🔍 Key Takeaways:

  • Lists are ordered and allow duplicates.
  • Use listOf() for immutable lists, mutableListOf() for editable ones.
  • Access elements by index or loop safely using Kotlin utilities.
  • Convert between mutable and immutable forms as needed.

⚙️ Practical Use:
Lists are used in shopping carts, API response parsing, form data handling, and recyclers in Android apps.


❓ FAQs – Kotlin Lists

Can Kotlin Lists contain duplicate values?
✅ Yes. Unlike Sets, Lists allow duplicates.


What is the difference between listOf() and mutableListOf()?
listOf() is read-only; mutableListOf() can be modified.


Can I convert a mutable list to immutable?
✅ Yes:

val immutable = mutableList.toList()

How do I sort a Kotlin list?
✅ Use .sorted():

val sortedList = list.sorted()

Can I filter items in a list based on a condition?
✅ Yes, use filter():

val filtered = list.filter { it.startsWith("A") }

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Kotlin – Lists (Mutable, Immutable)

Or Copy Link

CONTENTS
Scroll to Top