Lists
7 min · Scala
Hold many values under one name: Scala's immutable List.
Enemy 1 of 5
Creating and indexing a List
A List holds many values in order under one name. Lists in Scala never change once built, so adding an item gives you a new list.
This code makes a List of three fruits and prints the first one. Positions start at 0 and use parentheses. Press Run to see it.
Why this works
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.
Rena
Your AI tutor. She walks you through each step.
Asking for help is part of coding. Rena reads your code and gives you a hint. She is free with an account: 20 hints a day.