typestar

Lists in Scala

A tide log held in a List, extended at both ends and read back safely.

// a List literal holds its elements in order and never changes
val tideHeights: List[Int] = List(4, 7, 11, 9, 3)

// :: adds to the front and :+ appends to the back, both returning
// a new list rather than editing the old one
val withDawn: List[Int] = 2 :: tideHeights
val withDusk: List[Int] = tideHeights :+ 5

// the original still has its five readings after both operations
val stillFive: Boolean = tideHeights.length == 5

// head is the first element and tail is everything after it
val firstReading: Int = withDawn.head
val laterReadings: List[Int] = withDawn.tail

// head throws on an empty list, so headOption answers with an
// Option instead: Some for a reading, None for no readings at all
val maybeFirst: Option[Int] = List.empty[Int].headOption
val realFirst: Option[Int] = withDusk.headOption

How it works

  1. val tideHeights: List[Int] = List(4, 7, 11, 9, 3) is a list literal holding five readings in the order written.
  2. 2 :: tideHeights adds to the front and tideHeights :+ 5 appends to the back, each returning a new list, and stillFive confirms the original still has its five readings.
  3. withDawn.head is the first reading and withDawn.tail is the rest, while List.empty[Int].headOption hands back an Option[Int] where head would throw.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
811
Tokens
105
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 84 seconds.

Type this snippet

Step 1 of 3 in Collections, step 10 of 27 in Language basics.

← Previous Next →

Lists in other languages