🎓 A1Learner
🔍
0 of 45 lessons completed

Collection Choices

A collection is a group of values held together in one structure. The shape of the collection decides which changes are cheap.

A List serves the front

Prepending puts a new value first. This program prepends 1 and prints the new size, head, and last value.

@main def main(): Unit =
  val base = List(2, 3)
  val grown = 1 :: base
  println(grown.size)
  println(grown.head)
  println(grown.last)

A Vector serves the end

Appending puts a new value last. This program appends 3 and prints the new size, head, and last value.

@main def main(): Unit =
  val base = Vector(1, 2)
  val grown = base :+ 3
  println(grown.size)
  println(grown.head)
  println(grown.last)

Their natural orders differ

Prepending 1 through 5 reverses the order in a List. Appending the same values keeps the order in a Vector.

@main def main(): Unit =
  var list = List.empty[Int]
  var vector = Vector.empty[Int]
  var i = 1
  while i <= 5 do
    list = i :: list
    vector = vector :+ i
    i = i + 1
  println(list.size)
  println(list.head)
  println(vector.size)
  println(vector.head)
  println(vector.last)

Example

@main def main(): Unit =
  var list = List.empty[Int]
  var vector = Vector.empty[Int]
  var i = 1
  while i <= 3 do
    list = i :: list
    vector = vector :+ i
    i = i + 1
  println(list.size)
  println(list.head)
  println(vector.size)
  println(vector.head)

Key points

  • List: A linked chain of values where adding at the front is cheap.
  • Vector: A wide tree of values where adding at the end is cheap and position access is fast.
  • Prepend: Adding a value at the front is called a prepend.
  • Append: Adding a value at the end is called an append.
  • Head: The first value in a collection is its head.
  • Last: The final value in a collection is its last.

In this example, the loop prepends 1, 2, and 3 into a List and appends the same values into a Vector, and the printed heads show the List reversed to 3 while the Vector kept 1 first.

Note

In Scala, collections are immutable by default, so prepend and append both build a new collection.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

You add new values at the front again and again. Which collection fits best?