Thuta Learning
IntermediateProgrammingbeginner

Collections (Lists)

Relax. We'll talk through this in plain words — no textbook voice.

A list is a collection that stores values in order. In Kotlin, listOf() creates a read-only list, while mutableListOf() creates a list you can add to, remove from, and change. It's used all the time for things like product lists, menu lists, and user lists in apps.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3)
    println(numbers[0])

    val fruits = mutableListOf("apple", "banana")
    fruits.add("cherry")
    println(fruits)
}
You should see
1 [apple, banana, cherry]

Summary

Once you understand lists, you can easily process groups of data with loop, filter, and map.

Easy traps

  • If a list has 3 items, the valid indexes are only 0, 1, and 2. numbers[3] can throw an error.

Practical example — filter products

Practical example — filter products

kotlin
fun main() {
    val prices = listOf(12000, 5000, 25000, 8000)
    val affordable = prices.filter { it <= 10000 }

    println(affordable)
}

You'll know it worked when: [5000, 8000]