Lists
8 min · Kotlin
mutableListOf — Kotlin's resizable list.
Enemy 1 of 5
So far each variable has held one value. A List holds many values in order, and Kotlin gives you two flavors: listOf(...) creates a read-only list (you can look at its items but not add, remove, or replace any), while mutableListOf(...) creates one you're allowed to change after creation. Both are created the same way — by passing the initial items inside the parentheses — and both are indexed from 0 using square brackets: fruits[0] is the first item, fruits[1] the second, and so on.
Asking for an index that doesn't exist, like fruits[10] on a 3-item list, crashes the program at runtime with an IndexOutOfBoundsException rather than silently returning something like null or undefined. This is intentional — Kotlin (like most statically typed languages) prefers to fail loudly and immediately rather than let an invalid access quietly corrupt your program's behavior somewhere downstream.
Loading editor...