TExcelTAD
Home › Scala › Scala Vectors & Arrays

Scala Vectors & Arrays

List is great for working at the front of a sequence, but sometimes you need fast access to any position. Scala offers two indexed sequences: the immutable Vector and the mutable, Java-compatible Array. For growable mutable sequences there is ArrayBuffer.

Vector: the default indexed sequence

A Vector is an immutable tree with a very wide branching factor, so reading, updating and appending are all effectively constant time, even with millions of elements.

scala · try it yourself
@main def run(): Unit =
  val v = Vector("a", "b", "c", "d")
  println(v(2))
  println(v :+ "e")
  println("z" +: v)
  println(v.updated(1, "B"))
  println(v.slice(1, 3))
  println(v.length)
  println(s"original: $v")
c
Vector(a, b, c, d, e)
Vector(z, a, b, c, d)
Vector(a, B, c, d)
Vector(b, c)
4
original: Vector(a, b, c, d)

Tip: When you are not sure which immutable sequence to pick, choose Vector. Choose List when you mostly prepend and pattern match on head :: tail.

Array: fixed size, mutable

An Array is exactly a JVM array: fixed length, mutable elements, very fast. It is the right choice for performance-critical numeric code and for calling Java APIs.

scala · try it yourself
@main def run(): Unit =
  val temps = Array(18.5, 21.0, 19.2)
  temps(1) = 22.4               // arrays can be updated in place
  println(temps.mkString(", "))
  println(temps.length)
  println(temps.max)

  val grid = Array.ofDim[Int](2, 3)
  grid(1)(2) = 7
  println(grid.map(_.mkString(" ")).mkString("\n"))
18.5, 22.4, 19.2
3
22.4
0 0 0
0 0 7

Notice that we never call println(temps) directly. An array uses Java's default toString, which prints something like [D@1b6d3586 — a type tag plus a hash that changes from run to run. Always use mkString, or convert with toList/toSeq first:

scala · try it yourself
@main def run(): Unit =
  val letters = Array('x', 'y', 'z')
  println(letters.mkString("[", ",", "]"))
  println(letters.toList)
  println(letters.sameElements(Array('x', 'y', 'z')))
  println(letters == Array('x', 'y', 'z'))
[x,y,z]
List(x, y, z)
true
false

Arrays compare by reference with == (a Java legacy). Use sameElements to compare their contents.

ArrayBuffer: a growable mutable sequence

scala · try it yourself
import scala.collection.mutable.ArrayBuffer

@main def run(): Unit =
  val cart = ArrayBuffer("bread", "milk")
  cart += "eggs"
  cart ++= List("jam", "tea")
  cart -= "milk"
  cart.insert(0, "coffee")
  println(cart)
  println(cart.size)
  val frozen = cart.toVector
  println(frozen)
ArrayBuffer(coffee, bread, eggs, jam, tea)
5
Vector(coffee, bread, eggs, jam, tea)

A common pattern: build with an ArrayBuffer inside a method, then return an immutable Vector or List.

Choosing a sequence

Collection Mutable? Index access Prepend Append Typical use
List no slow fast slow recursion, pattern matching
Vector no fast fast fast general-purpose immutable data
Array elements yes, size no fastest — — numeric code, Java interop
ArrayBuffer yes fast slow fast building results step by step

All share the same methods

Because they all implement Seq, the familiar methods work everywhere:

scala · try it yourself
@main def run(): Unit =
  val v = Vector(3, 1, 4, 1, 5)
  val a = Array(3, 1, 4, 1, 5)
  println(v.sorted)
  println(a.sorted.mkString(","))
  println(v.map(_ * 2).filter(_ > 4))
  println(a.map(_ * 2).filter(_ > 4).toVector)
  println(v.sum == a.sum)
Vector(1, 1, 3, 4, 5)
1,1,3,4,5
Vector(6, 8, 10)
Vector(6, 8, 10)
true

Test yourself

Which collection is immutable and has fast access by index?

  1. List
  2. Vector
  3. Array
  4. ArrayBuffer

Why should you avoid println(myArray)?

  1. It does not compile
  2. It prints a JVM type tag and hash, not the elements
  3. It empties the array
  4. It prints the elements in reverse

What is Array(1, 2) == Array(1, 2)?

  1. true
  2. false
  3. A compile error
  4. It throws