Scala Arrays

There are two types of arrays in Scala just like in most programming languanges. Fixed length and variable length arrays.

Fixed-length arrays

If we know the size of the needed array and that size does not change, we can use the Array class.

val nums = new Array[Int](10)
nums: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
nums(0) = 10
nums
res2: Array[Int] = Array(10, 0, 0, 0, 0, 0, 0, 0, 0, 0)

A Scala Array is implemented as a Java array. For example the nums array above, inside the JVM is represented as int[] in the JVM.

Variable-length arrays

Variable-length arrays in Scala are utilized via the ArrayBuffer class

val b = ArrayBuffer[Int]()
cmd3.sc:1: not found: value ArrayBuffer
val b = ArrayBuffer[Int]()
        ^Compilation Failed
Compilation Failed

In contrast to the Array class, we need to explicitly import ArrayBuffer

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
b: ArrayBuffer[Int] = ArrayBuffer()

We can now add elements to the buffer

b += 1
res5: ArrayBuffer[Int] = ArrayBuffer(1)

or add more than one elements in one go

b += (5, 6, 7, 8, 9)
res6: ArrayBuffer[Int] = ArrayBuffer(1, 5, 6, 7, 8, 9)
b ++= Array(0, 0, 0)
res7: ArrayBuffer[Int] = ArrayBuffer(1, 5, 6, 7, 8, 9, 0, 0, 0)

There are various operations supported by the ArrayBuffer class; check the Scala documentation. One thing to note however is the following. Adding or removing elements at the end of an ArrayBuffer is an amortized constant time operation [1]. We can insert and remove elements at an arbitrary location, but those operations are not as efficient since all elements after that location must be shifted [1].

Traversing arrays

Scala is much more uniform compared to C++ when it comes to traversing arrays.

for(i <- 0 until b.length) println(b(i))
1
5
6
7
8
9
0
0
0

Note that we can also use a guard inside the for expression

for(i <- 0 until b.length if b(i) > 0) println(b(i))
1
5
6
7
8
9

Algorithms

Scala arrays have built-in some commin algorithms e.g. sum and sort, min and max

println("Max element of b " + b.max)
println("Min element of b " + b.min)
println("Sum of element of b " + b.sum)
Max element of b 9
Min element of b 0
Sum of element of b 36

The sorted method sorts an Array or ArrayBuffer and returns the sorted array without modifying the original [1].

val newB = b.sorted
println(b)
ArrayBuffer(1, 5, 6, 7, 8, 9, 0, 0, 0)
newB: ArrayBuffer[Int] = ArrayBuffer(0, 0, 0, 1, 5, 6, 7, 8, 9)

Note that you can sort an Array, but not an array buffer, in place [1]. Also note that for the min, max , and quickSort algorithms, the element type must have a comparison operation. This is the case for types with the Ordered trait [1].

References

  1. Cay Horstmann, Scala for the Impatient 1st Edition