All lessons

Lists

7 min · Scala

Hold many values under one name — Scala's immutable List.

Scala · Lists0/5 cleared

Enemy 1 of 5

Creating and indexing a List

So far every value has held exactly one thing — one name, one number, one string. Most real programs need to work with many values at once: a leaderboard of scores, a hand of cards, a list of usernames. Scala's `List` is the standard way to hold an ordered sequence of values under a single name.

Scala's `List` is immutable by default: once built, its contents never change. That might seem limiting coming from languages where arrays are mutated in place, but it buys you a strong guarantee — if you hand a list to another part of your program, you know it won't be silently altered behind your back. Operations that look like they "modify" a list (like adding an item) actually return a brand-new list, leaving the original exactly as it was.

`List("apple", "banana", "cherry")` builds a list from the given values, in that order. Elements are accessed by position, or index, using function-call syntax with parentheses — `fruits(0)` — not square brackets like many other languages use. Indexing starts at 0, so `fruits(0)` is the first element and `fruits(2)` is the third; this zero-based counting is standard across most programming languages, but it trips up nearly everyone the first time they meet it.

Asking for an index that doesn't exist — like `fruits(5)` on a 3-element list — throws a runtime exception rather than silently returning something like `null`, which is generally considered a feature: it surfaces the bug immediately instead of letting it hide.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: apple