Skip to content

Scala Arrays

An Array[T] in Scala is a mutable, fixed-size, indexed sequence of elements of type T. Arrays provide efficient random access to elements based on their index (starting from 0). They are directly mapped to Java arrays.

Note: While arrays are available and useful for performance-critical code or Java interop, idiomatic Scala often prefers immutable collections like Vector or List for general-purpose sequences, as they align better with functional programming principles.

You can create arrays in several ways:

// 1. Using 'new' with size (elements initialized to default: 0, false, null)
val numbers = new Array[Int](5) // Array of 5 integers, initialized to 0
val flags = new Array[Boolean](3) // Array of 3 booleans, initialized to false
val strings = new Array[String](2) // Array of 2 Strings, initialized to null
// 2. Using the companion object's 'apply' factory method (preferred)
val names = Array("Alice", "Bob", "Charlie") // Type inferred: Array[String]
val primes = Array(2, 3, 5, 7) // Type inferred: Array[Int]
val mixed = Array(1, "two", 3.0) // Type inferred: Array[Any]
// 3. Creating an empty array
val emptyInts = Array.empty[Int]

Use parentheses () with the index to access or update elements. Remember that arrays are 0-indexed.

val fruits = Array("Apple", "Banana", "Orange")
// Access elements
val firstFruit = fruits(0) // "Apple"
val secondFruit = fruits(1) // "Banana"
// Modify elements (Arrays are mutable)
fruits(1) = "Mango"
// Now fruits is Array("Apple", "Mango", "Orange")
@main def ArrayAccessDemo(): Unit = {
println(s"First fruit: $firstFruit")
println(s"Updated fruits: ${fruits.mkString(", ")}") // mkString is useful for display
// Accessing out of bounds causes ArrayIndexOutOfBoundsException
// println(fruits(3))
}

You can iterate and process arrays using for comprehensions or standard collection methods.

val data = Array(1.5, 2.0, 3.5, 4.0)
// Iteration using for loop
println("Processing with for loop:")
var sum = 0.0
for (x <- data) {
println(s"Processing $x")
sum += x
}
println(s"Sum: $sum")
// Iteration using indices
var product = 1.0
for (i <- 0 until data.length) { // Use 'until' for exclusive range
product *= data(i)
}
println(s"Product: $product")
// Using collection methods (more functional style)
val increasedData = data.map(x => x + 0.1)
println(s"Increased data: ${increasedData.mkString(", ")}")
val largeValues = data.filter(x => x > 2.5)
println(s"Large values: ${largeValues.mkString(", ")}")
data.foreach(x => println(s"Element: $x")) // Side-effecting iteration

Scala supports multi-dimensional arrays using Array.ofDim.

// Create a 2x3 matrix (2 rows, 3 columns) of integers
val matrix = Array.ofDim[Int](2, 3)
// Initialize the matrix
for (row <- 0 until matrix.length) {
for (col <- 0 until matrix(row).length) {
matrix(row)(col) = row * 10 + col
}
}
// Print the matrix
@main def MultiDimArrayDemo(): Unit = {
println("Matrix:")
for (row <- matrix) { // Iterate through rows (which are arrays)
println(row.mkString("\t")) // Print each row
}
// Access specific element
println(s"Element at (1, 2): ${matrix(1)(2)}") // Output: 12
}

Output:

Matrix:
0 1 2
10 11 12
Element at (1, 2): 12

Many useful methods are available directly or via the Array companion object.

Method/OperationDescription
lengthGet the size of the array.
apply(index)Access element at index (used via myArray(index) syntax).
update(index, value)Modify element at index (used via myArray(index) = value syntax).
map, filter, foreachStandard functional collection methods.
mkString(sep)Convert array elements to a string with a separator.
++Concatenate two arrays (returns a new array).
head, tail, last, initAccess first/last elements or subsequences.
slice(from, until)Extract a subarray.
sortedReturn a new sorted array (requires Ordering).
sum, min, max, productAggregate methods for numeric arrays.
Array.fill(n)(elem)Create an array of size n filled with elem.
Array.tabulate(n)(f)Create an array of size n where element i is f(i).
Array.range(start, end, step)Create an array with elements in a range.
val arr1 = Array(1, 2)
val arr2 = Array(3, 4)
val combined = arr1 ++ arr2 // Array(1, 2, 3, 4)
val evens = Array.range(0, 10, 2) // Array(0, 2, 4, 6, 8)
@main def ArrayOpsDemo(): Unit = {
println(s"Combined: ${combined.mkString(", ")}")
println(s"Evens: ${evens.mkString(", ")}")
}