Explain it simply
Explain it simply
A list is a collection that keeps values in order, like a shopping list on a sheet of paper. Every item has a position number (an index), and counting starts at 0, so the first item is at index 0. Product lists, menus and user lists in an app are all lists.
Kotlin has two kinds of list. The List built by listOf(...) can only be read; it has no add or remove. The MutableList built by mutableListOf(...) can be added to, removed from and changed. That split lets a type say whether a function only reads a list or is allowed to change it.
Problem → Why → Solution
The problem: reading a position that does not exist
A list with three items has valid indexes 0, 1 and 2 only. Writing numbers[3] because "there are three items, so take the third" crashes the program. This is an extremely common mistake, and calling first() on an empty list throws a different exception. The compiler warns about neither; both show up only at run time.
fun main() {
val numbers = listOf(1, 2, 3)
println(numbers[3]) // IndexOutOfBoundsException
val empty = emptyList<Int>()
println(empty.first()) // NoSuchElementException: List is empty.
}Why do these crash?
The size of a list is only known while the program runs, and the compiler does not check indexes against it. numbers[3] calls get(3), which on the JVM throws an exception with the message "Index 3 out of bounds for length 3". first() assumes a first element exists and throws on an empty list. Kotlin offers getOrNull and firstOrNull for the situations where an element might not be there.
Core concept: read-only and mutable lists
listOf(1, 2, 3) builds a List<Int>. That type has no add, remove or sort(), so list.add(4) fails with the compile error: unresolved reference 'add'. mutableListOf("apple", "banana") builds a MutableList<String> with every modifying operation. Do not confuse val with mutability: val fruits = mutableListOf(...) only means the variable fruits cannot be pointed at a different list; the contents can still be added to and removed from.
The important point is that read-only is not the same as immutable. The List type only says "you cannot change the list through this variable". If other code holds the same list as a MutableList, it can still change it and your List variable will show the change. To get a snapshot that nobody can alter, copy it with toList(). The deeper sections below show this with real output.
You read an element with list[i], where i runs from 0 to size - 1. An index outside that range throws an IndexOutOfBoundsException. The safe alternatives are getOrNull(i) (null when missing), getOrElse(i) { default }, firstOrNull() and lastOrNull(). Because they return null, they combine with ?. and ?: from the previous lesson, as in items.getOrNull(5) ?: "none".
Functions that produce new results matter too. filter { condition } keeps the elements that match, map { transform } returns each element transformed, and sorted() returns an ordered copy; all of them hand back a new list and leave the original alone. The part in curly braces, like { it < 1000 }, is a lambda, a small block of code that runs once per element, where it is the current element; a later lesson covers lambdas properly. joinToString() glues a list into a single string.
| Operation | Returns | Original changed? |
|---|---|---|
| filter, map, sorted | A new list | No |
| add, removeAt, sort() | Boolean, element, Unit | Yes (MutableList only) |
| list[i] | The element | No; throws if the index is missing |
| getOrNull(i) | The element or null | No |
- Pick listOf or mutableListOf
- Read with index, first or getOrNull
- map and filter build new lists
- Only a MutableList changes in place
A List type says "not through this variable", not "nobody can ever change it".
General pattern
val items: List<Type> = listOf(a, b, c)
val editable = mutableListOf(a, b)
editable.add(c)
val first = items[0]
val safe = items.getOrNull(index)
val result = items.filter { condition }.map { transform }The first two lines build a read-only and a mutable list, the third adds to the mutable one, the fourth and fifth read by index (the second form can return null), and the last chains filter and map to produce a new list.
Example: listOf, mutableListOf and getOrNull
This program shows both kinds of list. numbers is a read-only List and fruits is a MutableList you can add to. Predict what reading the missing index 5 with getOrNull gives, given that it raises no exception.
fun main() {
val numbers = listOf(1, 2, 3)
println(numbers[0])
val fruits = mutableListOf("apple", "banana")
fruits.add("cherry")
println(fruits)
println("size: ${fruits.size}")
println(fruits.getOrNull(5))
}Code breakdown
- Read-only list
val numbers = listOf(1, 2, 3)Kotlin infers numbers as a List<Int>. You cannot call add or remove on it; writing either one does not compile.
- Index access
println(numbers[0])Index 0 is the first element, so this prints 1. numbers[3] would be a missing position and throw an exception.
- Mutable list
val fruits = mutableListOf("apple", "banana")This builds a MutableList<String>. Because of val, fruits cannot be pointed at another list, but the contents can change.
- Changing the list
fruits.add("cherry")This appends "cherry" to the end of the list, so printing it gives [apple, banana, cherry] and the size becomes 3.
- Safe read
println(fruits.getOrNull(5))The list has only three elements, so index 5 does not exist, but unlike fruits[5] this returns null instead of throwing, so null is printed.
1
[apple, banana, cherry]
size: 3
null- Receive an index i
- Is i between 0 and size - 1?
- If yes, return the element
- If no, throw or return null
list[i]
Throws IndexOutOfBoundsException
getOrNull(i)
Returns null, so use ?: for a default
Read-only is not immutable
In the code below, source is a MutableList and view is a List<Int> variable pointing at the very same object: one list seen through two types. As soon as source.add(4) runs, printing view shows the 4. toList() builds a fresh copy of the list as it is at that moment, so later changes do not touch the copy.
fun main() {
val source = mutableListOf(1, 2, 3)
val view: List<Int> = source
println(view)
source.add(4)
println(view)
val copy = source.toList()
source.add(5)
println(copy)
println(source)
}The output is [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4, 5]. The second line shows the "read-only" list changing, and the third (the copy) lacks the 5 because the copy is its own list. A function that accepts a List promises not to change it, but it cannot know whether someone else is changing it.
Handling missing elements safely
The code below catches the exceptions with try/catch and prints their messages (error handling with try/catch is covered in a later lesson), then shows three safe alternatives. getOrNull returns null, getOrElse(3) { -1 } returns the block's value when the index is missing, and firstOrNull() gives null on an empty list.
fun main() {
val numbers = listOf(1, 2, 3)
try {
println(numbers[3])
} catch (e: IndexOutOfBoundsException) {
println("caught: ${e.message}")
}
try {
println(emptyList<Int>().first())
} catch (e: NoSuchElementException) {
println("caught: ${e.message}")
}
println(numbers.getOrNull(3))
println(numbers.getOrElse(3) { -1 })
println(emptyList<Int>().firstOrNull())
}The output is "caught: Index 3 out of bounds for length 3", "caught: List is empty.", null, -1 and null. These messages are the ones Kotlin shows on the JVM; Kotlin/JS or Native may word them differently. Which tool to use depends on whether a missing element is a normal possibility (getOrNull) or a programmer error (list[i], and let the exception surface).
filter, map, sorted and joinToString
These functions return new lists, so you can chain them. The example below turns prices into several results with filter, map, sorted and sortedDescending, prints each on its own line, then prints prices itself to confirm it did not change. joinToString(separator = " | ") lets you choose the separator between elements.
fun main() {
val prices = listOf(1200, 350, 800, 2500, 90)
val cheap = prices.filter { it < 1000 }
val doubled = prices.map { it * 2 }
val ascending = prices.sorted()
val descending = prices.sortedDescending()
println(cheap)
println(doubled)
println(ascending)
println(descending)
println(prices)
println(prices.joinToString(separator = " | "))
println(prices.first())
println(prices.firstOrNull { it > 5000 })
println(prices.map { "$it MMK" }.joinToString(", "))
}The output is [350, 800, 90], [2400, 700, 1600, 5000, 180], [90, 350, 800, 1200, 2500], [2500, 1200, 800, 350, 90], the untouched original [1200, 350, 800, 2500, 90], "1200 | 350 | 800 | 2500 | 90", 1200, null and "1200 MMK, 350 MMK, 800 MMK, 2500 MMK, 90 MMK". firstOrNull { it > 5000 } gives the first matching element, or null. On a MutableList, sort() sorts in place and returns Unit, so assigning its result to a val is a frequent slip.
In real projects
Where this shows up in real projects
Lists are the most used data structure in Kotlin programs. Database query results, the JSON arrays an API returns, the items on a screen, the lines of a log file and the products in a shopping cart are all held as Lists. Combining filter and map answers questions such as "the names of the products under 1000" in a single line.
When a public function accepts a List<T> it declares that it will not change it, and when it returns data it is safer not to hand out an internal MutableList directly but a toList() copy, so outside code cannot change the class's internals by accident. Preferring getOrNull over list[i] for indexes that come from user input or outside data also removes a whole family of production crashes.
Common mistakes
Common mistakes
1. Treating size as the last index
A list of three items has 2 as its last index, which is size - 1. list[list.size] is a missing position and throws. To get the last element use last() or lastOrNull(); there is no index to calculate.
2. Expecting to modify a listOf list
After val l = listOf(1, 2, 3), writing l.add(4) gives: unresolved reference 'add'. l.sort() fails the same way. If you need to modify it, use mutableListOf, or take the result as a new list (sorted(), l + 4).
3. Using the result of sort()
val s: List<Int> = m.sort() fails with: initializer type mismatch: expected 'List<Int>', actual 'Unit', because sort() sorts the mutable list in place and returns Unit. If you want a new ordered result use sorted(); the original list stays unchanged.
4. Trusting a read-only List to be immutable
A function may accept a List<Int> while the caller passed a MutableList and keeps changing it, so what the function sees can change underneath it. If a value must not change, take a snapshot with toList().
Best practices
Best practices
- Start with listOf and switch to mutableListOf only when you have a reason to add or remove.
- Declare function parameters as List<T>, and use MutableList<T> only in functions that must change it.
- When an index comes from outside or the list may be empty, prefer getOrNull and firstOrNull over list[i] and first().
Mini challenge
Mini challenge: a bookshelf
Manage a bookshelf with a MutableList and write three helper functions that report on it. The helpers accept a List and must not change the original.
- shortTitles(titles, maxLength) filters the titles with length ≤ maxLength and returns a new list
- summary(titles) returns "no books" for an empty list, otherwise the sorted titles joined with " / "
- titleAt(titles, index) reads with getOrNull and returns "(none)" when the index is missing
- In main start from mutableListOf("Kotlin Basics", "Zen", "Data Structures", "Go"), add "Algebra" and remove "Go"
fun shortTitles(titles: List<String>, maxLength: Int): List<String> {
// TODO: keep only titles whose length is at most maxLength
}
fun summary(titles: List<String>): String {
// TODO: "no books" for an empty list, else sorted titles joined with " / "
}
fun titleAt(titles: List<String>, index: Int): String {
// TODO: the title at index, or "(none)" when that index does not exist
}
fun main() {
// TODO: build the shelf, add "Algebra", remove "Go"
// TODO: print summary(shelf), shortTitles(shelf, 7), titleAt(shelf, 1) and
// titleAt(shelf, 10), then summary(emptyList())
}Expected: The program should print: Algebra / Data Structures / Kotlin Basics / Zen [Zen, Algebra] Zen (none) no books
Show hint
Use filter { it.length <= maxLength } and getOrNull(index) ?: "(none)". Start summary with if (titles.isEmpty()) return "no books" and end it with titles.sorted().joinToString(" / "). remove("Go") removes the first matching element. You can pass emptyList() to summary because the parameter type supplies the element type.
Show solution
fun shortTitles(titles: List<String>, maxLength: Int): List<String> {
return titles.filter { it.length <= maxLength }
}
fun summary(titles: List<String>): String {
if (titles.isEmpty()) return "no books"
return titles.sorted().joinToString(" / ")
}
fun titleAt(titles: List<String>, index: Int): String {
return titles.getOrNull(index) ?: "(none)"
}
fun main() {
val shelf = mutableListOf("Kotlin Basics", "Zen", "Data Structures", "Go")
shelf.add("Algebra")
shelf.remove("Go")
println(summary(shelf))
println(shortTitles(shelf, 7))
println(titleAt(shelf, 1))
println(titleAt(shelf, 10))
println(summary(emptyList()))
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- listOf builds a read-only List and mutableListOf a MutableList, but read-only is not immutable; take a snapshot with toList().
- Indexes start at 0; list[i] on a missing position throws IndexOutOfBoundsException and first() throws NoSuchElementException on an empty list.
- getOrNull, getOrElse and firstOrNull read elements without exceptions and combine with ?: for a default.
- filter, map and sorted return new lists and leave the original alone, while sort() reorders a MutableList in place and returns Unit; joinToString turns a list into one string.
Kotlin language guide — Kotlin