Skip to the workspace
Pebellslearn by building
Collections, Ranges and Sequences  ›  Lesson

Arrays and Lists

Lists 15 minAn array is a fixed-size block of indexed slots, while a list is an ordered collection that can be read-only or growable; both are indexed from zero.

kotlin / Arrays and Lists

Explore each scene at your own pace.

01 · The rule

The rule

Arrays and Lists

An array is a fixed-size block of indexed slots, while a list is an ordered collection that can be read-only or growable; both are indexed from zero.

Choose fixed indexed storage or a list and inspect element access and copying.

The café menu has several drinks, and the till records many orders. Storing each in its own variable, drink1, drink2, drink3, falls apart the moment a new drink arrives. Kotlin offers arrays and lists to hold many values under one name.

The rule

Array: fixed slots. List: ordered items. Both count from zero.

Arrays have a size fixed at creation. You can change what is in a slot, but you cannot add or remove slots.

val menu = arrayOf("latte", "mocha", "chai")
menu[1] = "flat white"          // change a slot: allowed
println(menu.size)              // 3
val week = IntArray(7)          // seven zeros, one per day
val doubles = Array(3) { it * 2 }   // 0, 2, 4

IntArray, DoubleArray and friends store plain numbers efficiently. Array(3) { it * 2 } fills each slot by running the braces with it as the index.

Lists are Kotlin's everyday choice. listOf makes a read-only list; mutableListOf makes one you can grow and shrink.

val drinks = listOf("latte", "mocha", "chai")
println(drinks[0])              // latte
println(drinks.first())         // latte
println(drinks.last())          // chai
println(drinks.indexOf("tea"))  // -1: not found
println("chai" in drinks)       // true

val orders = mutableListOf("latte")
orders.add("chai")              // [latte, chai]
orders.removeAt(0)              // [chai]

Reading past the end, drinks[3], throws IndexOutOfBoundsException. drinks.getOrNull(3) returns null instead.

Two differences show up when printing and comparing. println(drinks) shows [latte, mocha, chai], but an array needs contentToString(). And == on two lists compares their items, while == on two arrays asks whether they are the same object; use contentEquals for arrays.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.