Scala Arrays
Overview of Scala arrays
There are two types of arrays in Scala just like in most programming languanges. Fixed length and variable 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(0) = 10
nums
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 in Scala are utilized via the ArrayBuffer class
val b = ArrayBuffer[Int]()
In contrast to the Array class, we need to explicitly import ArrayBuffer
import scala.collection.mutable.ArrayBuffer
val b = ArrayBuffer[Int]()
We can now add elements to the buffer
b += 1
or add more than one elements in one go
b += (5, 6, 7, 8, 9)
b ++= Array(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].
Scala is much more uniform compared to C++ when it comes to traversing arrays.
for(i <- 0 until b.length) println(b(i))
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))
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)
The sorted method sorts an Array or ArrayBuffer and returns the sorted array without modifying the original [1].
val newB = b.sorted
println(b)
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].
- Cay Horstmann,
Scala for the Impatient 1st Edition