Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Collections

Arrays, Seq and Buffers

Tour the Scala collections library: immutable vs mutable, the Seq hierarchy, Array, ArrayBuffer, indexing, updating, sorting and when to pick each sequence type.

The Scala collections library is one of the language's best features. Almost every collection supports the same rich set of operations, so once you learn them on a list, you can use them on an array, a set or a map. In this lesson we start with the big picture and then the sequence types you reach for first: Seq, Array and ArrayBuffer. The Scala code is read-only; runnable Java and Kotlin demos show the same ideas.

Immutable and mutable collections

Scala has two parallel families:

  • scala.collection.immutable: never change after creation. This is the default. List, Vector, Set, Map come from here without any import.
  • scala.collection.mutable: can be changed in place, such as ArrayBuffer, mutable.Map and mutable.Set. You import them explicitly.

"Immutable" does not mean slow or awkward. An "update" returns a new collection that shares most of its structure with the old one, so it is cheap.

flowchart TD
  Iterable --> Seq
  Iterable --> Set
  Iterable --> Map
  Seq --> IndexedSeq
  Seq --> LinearSeq
  IndexedSeq --> Vector
  IndexedSeq --> ArrayBuffer
  LinearSeq --> List

Seq is an ordered sequence. List is a linked list (fast at the head), Vector is fast at any index, ArrayBuffer is a growable mutable array.

Seq

Seq is the general immutable sequence. Creating one with Seq(...) gives you a List underneath:

SCALA
val numbers = Seq(10, 20, 30)
numbers.head        // 10
numbers.tail        // List(20, 30)
numbers(1)          // 20
numbers.length      // 3
numbers.isEmpty     // false
numbers :+ 40       // List(10, 20, 30, 40): append
0 +: numbers        // List(0, 10, 20, 30): prepend
numbers ++ Seq(7)   // List(10, 20, 30, 7): concatenate

The original numbers is unchanged. The result of each operation is a new sequence. Use Seq as a parameter type when you do not care which sequence you receive:

SCALA
def average(xs: Seq[Double]): Double = xs.sum / xs.length

Details about the concrete types are in Lists and Vectors.

Array

Array is Java's array, with Scala conveniences. It has a fixed size, uses mutable elements and is stored contiguously, so it is fast and compact.

SCALA
val grades = Array(90, 75, 82)
grades(0)                 // 90
grades(1) = 80            // mutate in place: Array(90, 80, 82)
grades.length             // 3

val zeros = Array.fill(4)(0)         // Array(0, 0, 0, 0)
val squares = Array.tabulate(5)(i => i * i) // Array(0, 1, 4, 9, 16)
val empty = new Array[String](3)     // Array(null, null, null)

Unlike a Java array, a Scala Array has all collection methods thanks to implicit wrapping: grades.map(_ + 5), grades.sum, grades.max, grades.sorted. Indexing uses parentheses, not brackets.

A few cautions:

  • println(grades) prints something like [I@6d06d69c. Use grades.mkString(", ") or grades.toList to print the contents.
  • Arrays are invariant and compare by reference: Array(1) == Array(1) is false. Use sameElements or compare as lists.
  • Out-of-range access throws ArrayIndexOutOfBoundsException.

Here is the Java version of those behaviours, runnable:

Java Array printing and equality pitfalls (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two-dimensional arrays are arrays of arrays:

SCALA
val grid = Array.ofDim[Int](2, 3)
grid(1)(2) = 7
// Array(Array(0, 0, 0), Array(0, 0, 7))

ArrayBuffer

When you need a growable sequence that you change in place, use ArrayBuffer:

SCALA
import scala.collection.mutable.ArrayBuffer

val buf = ArrayBuffer(1, 2, 3)
buf += 4                  // ArrayBuffer(1, 2, 3, 4)
buf ++= List(5, 6)        // adds many
buf.prepend(0)            // ArrayBuffer(0, 1, 2, 3, 4, 5, 6)
buf.remove(0)             // removes and returns index 0
buf -= 3                  // removes the first 3
buf.insert(1, 99)         // inserts at index 1
buf(0) = -1               // update by index
buf.clear()               // empty it

Because += and -= mutate and return the buffer, you can use them on a val: the reference is not rebound. Contrast with an immutable Vector in a var, where v = v :+ 4 creates a new vector each time.

ArrayBuffer plays the role of Java's ArrayList. Run the equivalent:

Java Growable list in Java (ArrayBuffer comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When a mutable buffer is only a stepping stone, convert it at the end:

SCALA
val result = buf.toList      // or .toVector, .toSeq, .toArray

A good pattern is to build up with a ArrayBuffer inside a method and return an immutable List, so no mutable state escapes.

Sorting and searching

SCALA
val words = Seq("pear", "fig", "banana")
words.sorted                       // List(banana, fig, pear)
words.sortBy(_.length)             // List(fig, pear, banana)
words.sortWith(_ > _)              // List(pear, fig, banana)
words.indexOf("fig")               // 1
words.contains("kiwi")             // false
words.exists(_.startsWith("b"))    // true

sorted uses the natural ordering of the element type; sortBy sorts by a derived key; sortWith takes a comparison function. All of them return a new collection. Array.sorted returns a new array, and scala.util.Sorting.quickSort(arr) sorts in place.

Choosing a sequence

You need Use
A default immutable sequence List or Vector
Fast random access, immutable Vector
Fast prepend and pattern matching List
Mutable, growable ArrayBuffer
Fixed size, maximum speed, Java interop Array
Function parameter that accepts any ordered collection Seq

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does numbers :+ 40 do to an immutable Seq?

    Immutable collections never change; :+ returns a new collection with the element added at the end.
  2. 2. How do you read the first element of an Array named grades in Scala?

    Scala uses parentheses for indexing: grades(0) calls apply(0).
  3. 3. Which collection is the usual growable, mutable sequence?

    ArrayBuffer (in scala.collection.mutable) can grow and shrink in place.
  4. 4. Why does println(Array(1, 2)) show text like [I@6d06d69c?

    A Scala Array is a Java array, whose toString is the type and hash. Print with mkString or toList.

Summary

  • Collections are immutable by default; mutable ones live in scala.collection.mutable.
  • Seq is the general ordered sequence; operations like :+, +:, ++ return new collections.
  • Array is the Java array: fixed size, mutable elements, index with ().
  • ArrayBuffer is the growable mutable sequence; convert with .toList when done.
  • sorted, sortBy, sortWith and contains work across all sequences.

Next: Lists and Vectors