Scala Lists
List is the classic Scala collection: an immutable, singly linked list. Adding to the front is instant, reading the first element is instant, and the list can never change after it is created — every "modification" returns a new list that shares most of its structure with the old one.
Creating lists
@main def run(): Unit =
val primes = List(2, 3, 5, 7)
val names = List("Ines", "Omar", "Yuki")
val empty = List.empty[Int]
val built = 1 :: 2 :: 3 :: Nil
val filled = List.fill(3)("ha")
val tabulated = List.tabulate(5)(i => i * i)
println(primes)
println(names)
println(empty)
println(built)
println(filled)
println(tabulated)List(2, 3, 5, 7)
List(Ines, Omar, Yuki)
List()
List(1, 2, 3)
List(ha, ha, ha)
List(0, 1, 4, 9, 16)
Nil is the empty list, and :: (pronounced "cons") puts an element in front of a list.
Accessing elements
@main def run(): Unit =
val xs = List(10, 20, 30, 40)
println(xs.head)
println(xs.tail)
println(xs.last)
println(xs(2))
println(xs.length)
println(xs.isEmpty)
println(xs.headOption)
println(List.empty[Int].headOption)
println(xs.lift(9))10
List(20, 30, 40)
40
30
4
false
Some(10)
None
None
Note:
headon an empty list andxs(i)with a bad index throw exceptions.headOptionandlift(i)return anOptioninstead, which is safer.
"Changing" a list
Every operation returns a new list; the original stays the same.
@main def run(): Unit =
val base = List(2, 3)
val prepended = 1 :: base
val appended = base :+ 4
val joined = base ++ List(8, 9)
val updated = base.updated(0, 99)
val removed = joined.filterNot(_ == 8)
println(prepended)
println(appended)
println(joined)
println(updated)
println(removed)
println(s"base is still $base")List(1, 2, 3)
List(2, 3, 4)
List(2, 3, 8, 9)
List(99, 3)
List(2, 3, 9)
base is still List(2, 3)
Performance at a glance
| Operation | Cost on List |
|---|---|
x :: xs, head, tail |
constant (fast) |
xs :+ x, last, xs(i), length |
proportional to the length (slow for big lists) |
xs ++ ys |
proportional to the length of xs |
If you need fast access by index or fast appends, use a Vector (next chapter).
Common list methods
@main def run(): Unit =
val scores = List(72, 95, 58, 88, 95)
println(scores.sum)
println(scores.max)
println(scores.sorted)
println(scores.sorted.reverse)
println(scores.distinct)
println(scores.contains(58))
println(scores.indexOf(95))
println(scores.take(2))
println(scores.drop(3))
println(scores.count(_ >= 80))
println(scores.mkString(" | "))408
95
List(58, 72, 88, 95, 95)
List(95, 95, 88, 72, 58)
List(72, 95, 58, 88)
true
1
List(72, 95)
List(88, 95)
3
72 | 95 | 58 | 88 | 95
Pattern matching on lists
Lists are built from :: and Nil, so you can match on those shapes. This is the natural way to write recursive list functions.
def sumAll(xs: List[Int]): Int = xs match
case Nil => 0
case head :: tail => head + sumAll(tail)
def describe(xs: List[String]): String = xs match
case Nil => "nobody"
case List(one) => one
case List(a, b) => s"$a and $b"
case first :: rest => s"$first and ${rest.size} others"
@main def run(): Unit =
println(sumAll(List(4, 5, 6)))
println(describe(Nil))
println(describe(List("Pia")))
println(describe(List("Pia", "Leo")))
println(describe(List("Pia", "Leo", "Max", "Zoe")))15
nobody
Pia
Pia and Leo
Pia and 3 others
Mutable alternative: ListBuffer
When you build a list step by step in a loop, a ListBuffer avoids creating many intermediate lists. Convert it to an immutable List at the end.
import scala.collection.mutable.ListBuffer
val buf = ListBuffer[Int]()
for i <- 1 to 3 do buf += i * 10
val result = buf.toList // List(10, 20, 30)Test yourself
What does 0 :: List(1, 2) produce?
List(1, 2, 0)List(0, 1, 2)List(0, List(1, 2))- A compile error
Which operation is fast (constant time) on a List?
xs.lastxs(1000)xs.headxs :+ 5
What does List.empty[Int].headOption return?
0nullNone- It throws an exception