Exploring Immutable Arrays in Scala: A Deep Dive into Vectors

Scala Array is not located in the scala.collection.mutable package, however, they are in fact mutable

val arr = Array(1,2,3)
arr(1) = 3
println(arr.mkString(",")) // 1,3,3

Immutable alternative to Scala Array is Scala Vector

val arr = Vector(1,2,3)
println(arr.updated(1,3).mkString(",")) // 1,3,3
println(arr.mkString(",")) // 1,2,3 because original array remains unchanged

Vector provides O(1) asymptotic time complexity prepend, append, random read, random write operations

Most important methods of Vector class:

MethodDescription
vector.update(index, V)random write, returns a new vector with an updated value V at the specified index
vector(index)random read, returns a value of the index element
vector.prepended(V)returns a new vector with prepended value V
vector.appended(v)returns a new vector with appended value V