All lessons

Lists

8 min · Kotlin

mutableListOf: Kotlin's resizable list.

Kotlin · Lists0/5 cleared

Enemy 1 of 5

This code makes a list of three fruits and prints the first one. Lists count from 0, so fruits[0] is the first item. Press Run to see it.

Why this works

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.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.