← Back to Kotlin Course | Chapter 8: Collections | Lesson 1 of 7

List Basics

A List is an ordered row of items that you can look at, but not change, once you've made it with listOf.

Creating a List

listOf(...) builds a read-only List containing the given elements in the given order, which is the most common way to work with a fixed collection of values.

Example: Creating a List

markup
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    println(fruits)
}

Accessing Elements by Index

Elements are retrieved using square brackets with a zero-based index, such as fruits[0] for the first element.

Example: Accessing Elements by Index

markup
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    println("First: ${fruits[0]}")
    println("Last: ${fruits[fruits.size - 1]}")
}

Common List Properties and Functions

List provides convenient read-only members like .size, .first(), .last(), .isEmpty(), and .contains(item) for inspecting the collection without mutating it.

Example: Common List Properties and Functions

markup
fun main() {
    val fruits = listOf("apple", "banana", "cherry")
    println("Size: ${fruits.size}")
    println("First: ${fruits.first()}")
    println("Contains banana: ${fruits.contains("banana")}")
}

Lists Are Read-Only, Not Necessarily Immutable

A List reference cannot itself add or remove elements, but if it points to the same object as a MutableList reference elsewhere, changes made through that other reference are still visible.

Note: This is why List is called read-only rather than immutable in Kotlin's terminology.

Example: Lists Are Read-Only, Not Necessarily Immutable

markup
fun main() {
    val mutable = mutableListOf("a", "b")
    val readOnlyView: List<String> = mutable
    mutable.add("c")
    println(readOnlyView)
}
Common Mistakes
  1. Trying to call .add() on a List created with listOf(), forgetting it is read-only and not necessarily mutable.
  2. Assuming a read-only List can never change; if its underlying value is a MutableList, changes made through that reference are still visible through the read-only view.
  3. Using index-based access without checking bounds, causing an IndexOutOfBoundsException on an invalid index.
Chapter Summary
  • listOf(...) creates a read-only List -- you cannot add, remove, or replace elements through it.
  • Elements are accessed by zero-based index using list[index] or list.get(index).
  • List provides many read-only helper functions like .size, .first(), .last(), and .contains().
  • A read-only List type does not guarantee true immutability if another reference to the same underlying collection is mutable.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.