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
val tideHeights: List[Int] = List(4, 7, 11, 9, 3)is a list literal holding five readings in the order written.2 :: tideHeightsadds to the front andtideHeights :+ 5appends to the back, each returning a new list, andstillFiveconfirms the original still has its five readings.withDawn.headis the first reading andwithDawn.tailis the rest, whileList.empty[Int].headOptionhands back anOption[Int]whereheadwould throw.
Keywords and builtins used here
BooleanIntListOptionval
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.
Step 1 of 3 in Collections, step 10 of 27 in Language basics.