Arrays in Scala
An Array in Scala is a fixed-size, indexed collection whose elements have the same type. Arrays are mutable, so an element can be replaced after the array is created.
Each array element is accessed through a zero-based index. The first element is at index 0, and the last element is at index array.length - 1.
An array can contain primitive values such as integers and doubles, strings, or objects of a class type.
Scala supports one-dimensional arrays and multidimensional arrays. This tutorial explains how to declare, initialize, access, update, traverse, fill, append to, and transform Scala arrays.
Scala One Dimensional Array
Following is the syntax to declare an Integer Array with an initial size.
var arrayname:Array[Type] = new Array[Type](size)
where
- arrayname is the identifier to the Array.
Typeis the datatype or the class type of the elements in the Array.sizeis the initial size of the array.
You can skip the array type declaration right after the variable name.
var arrayname = new Array[Type](size)
or ignore the type declaration in new array phrase.
var arrayname:Array[Type] = new Array(size)
You can also initialize an Array with elements during its declaration.
var arrayname = Array(element1, element2, .., elementN)
Default Values in a Newly Created Scala Array
When an array is created with new Array[Type](size), Scala initializes every position with the default value for that element type. Numeric arrays contain zero values, Boolean arrays contain false, and arrays of reference types contain null.
val numbers = new Array[Int](4)
val flags = new Array[Boolean](3)
val names = new Array[String](2)
println(numbers.mkString(", "))
println(flags.mkString(", "))
println(names.mkString(", "))
0, 0, 0, 0
false, false, false
null, null
Initialize a Scala Array with Values
The Array companion object can create an array directly from a sequence of values. Scala usually infers the element type from those values.
val scores = Array(82, 91, 76, 88)
val cities = Array("Delhi", "Mumbai", "Chennai")
println(scores.mkString(", "))
println(cities.mkString(" | "))
82, 91, 76, 88
Delhi | Mumbai | Chennai
You can provide an explicit type when the intended element type is not obvious or when values should be widened to a common type.
val measurements: Array[Double] = Array(12.5, 10.0, 18.75)
val mixedNumbers: Array[Double] = Array(1, 2.5, 3)
Access Scala Array Elements by Index
Use parentheses after the array name to read an element. Valid indexes range from 0 through length - 1.
val languages = Array("Scala", "Java", "Kotlin")
println(languages(0))
println(languages(2))
println(languages(languages.length - 1))
Scala
Kotlin
Kotlin
Trying to read an index outside the valid range causes an ArrayIndexOutOfBoundsException. Methods such as isDefinedAt can be used when an index must be checked before access.
val values = Array(10, 20, 30)
val index = 2
if (values.isDefinedAt(index)) {
println(values(index))
} else {
println("Invalid array index")
}
Update Elements in a Mutable Scala Array
Although an array has a fixed length, its existing elements can be changed. Assign a new value to the required index.
val prices = Array(100, 150, 200)
prices(1) = 175
println(prices.mkString(", "))
100, 175, 200
The reference can be declared with val because the reference still points to the same array. The elements inside that array remain mutable.
Find the Length and Valid Index Range of a Scala Array
Use length or size to obtain the number of elements. Use indices when a loop needs every valid array index.
val numbers = Array(4, 8, 12, 16)
println(numbers.length)
println(numbers.size)
println(numbers.indices)
4
4
Range 0 until 4
Traverse a Scala Array with for and foreach
A for loop can iterate over the values directly.
val numbers = Array(5, 10, 15)
for (number <- numbers) {
println(number)
}
Use indices when both the index and value are required.
val fruits = Array("Apple", "Banana", "Orange")
for (index <- fruits.indices) {
println(s"$index: ${fruits(index)}")
}
0: Apple
1: Banana
2: Orange
The foreach method is a concise choice when only each element is needed.
val numbers = Array(2, 4, 6)
numbers.foreach(number => println(number))
Create Repeated Values with Array.fill
Array.fill creates an array of a specified length and evaluates the supplied expression for each position.
val zeros = Array.fill(5)(0)
val labels = Array.fill(3)("pending")
println(zeros.mkString(", "))
println(labels.mkString(", "))
0, 0, 0, 0, 0
pending, pending, pending
The value expression is evaluated separately for every element. This matters when creating arrays of mutable objects.
Create Generated Values with Array.tabulate
Array.tabulate creates each element from its index. It is useful for sequences derived from a formula.
val squares = Array.tabulate(6)(index => index * index)
println(squares.mkString(", "))
0, 1, 4, 9, 16, 25
Common Scala Array Methods
Scala arrays support many collection operations. Some methods return a new array, while aggregate methods return a single result.
val numbers = Array(3, 8, 1, 6, 4)
val doubled = numbers.map(_ * 2)
val even = numbers.filter(_ % 2 == 0)
val sorted = numbers.sorted
val total = numbers.sum
val largest = numbers.max
val containsSix = numbers.contains(6)
println(doubled.mkString(", "))
println(even.mkString(", "))
println(sorted.mkString(", "))
println(total)
println(largest)
println(containsSix)
6, 16, 2, 12, 8
8, 6, 4
1, 3, 4, 6, 8
22
8
true
Frequently used array operations include:
maptransforms every element and returns a new collection.filterkeeps elements that satisfy a condition.sortedreturns the elements in sorted order.sum,min, andmaxcalculate aggregate values for supported element types.containschecks whether a value is present.reversereturns the elements in reverse order.distinctremoves duplicate values.mkStringjoins elements into a readable string.
Append Elements to a Scala Array
A Scala array has a fixed length, so it cannot grow in place. The :+, +:, and ++ operations create a new array containing the added values.
val original = Array(20, 30)
val appended = original :+ 40
val prepended = 10 +: original
val combined = original ++ Array(40, 50)
println(appended.mkString(", "))
println(prepended.mkString(", "))
println(combined.mkString(", "))
20, 30, 40
10, 20, 30
20, 30, 40, 50
When values must be added and removed repeatedly, a mutable collection such as ArrayBuffer is usually more suitable than repeatedly creating new arrays.
import scala.collection.mutable.ArrayBuffer
val numbers = ArrayBuffer(10, 20)
numbers += 30
numbers ++= Seq(40, 50)
println(numbers.mkString(", "))
Copy and Clone a Scala Array
Assigning an array to another variable does not copy its elements. Both variables refer to the same mutable array.
val first = Array(1, 2, 3)
val sameReference = first
sameReference(0) = 99
println(first.mkString(", "))
99, 2, 3
Use clone() when an independent shallow copy is required.
val original = Array(1, 2, 3)
val copied = original.clone()
copied(0) = 99
println(original.mkString(", "))
println(copied.mkString(", "))
1, 2, 3
99, 2, 3
Compare Scala Arrays by Content
To compare array elements in order, use sameElements. This clearly expresses that the contents, rather than the array references, are being compared.
val first = Array(1, 2, 3)
val second = Array(1, 2, 3)
val third = Array(3, 2, 1)
println(first.sameElements(second))
println(first.sameElements(third))
true
false
Scala Multidimensional Array
A multidimensional array can represent rows and columns. Array.ofDim is a direct way to create a rectangular two-dimensional array.
val matrix = Array.ofDim[Int](2, 3)
matrix(0)(0) = 10
matrix(0)(1) = 20
matrix(0)(2) = 30
matrix(1)(0) = 40
matrix(1)(1) = 50
matrix(1)(2) = 60
for (row <- matrix) {
println(row.mkString(" "))
}
10 20 30
40 50 60
You can also initialize a two-dimensional array from nested arrays.
val matrix = Array(
Array(1, 2, 3),
Array(4, 5, 6)
)
println(matrix(1)(2))
6
Because a multidimensional Scala array is an array of arrays, its rows can also have different lengths. Such a structure is commonly called a jagged array.
Convert Between Scala Array and List
Use toList to convert an array to an immutable List, and use toArray to convert a list or another collection to an array.
val numbers = Array(1, 2, 3)
val numberList = numbers.toList
val copiedArray = numberList.toArray
println(numberList)
println(copiedArray.mkString(", "))
List(1, 2, 3)
1, 2, 3
Use Scala Arrays with Java APIs
Scala arrays are represented using Java Virtual Machine arrays, so they can usually be passed directly to Java methods that expect a compatible array type.
val names: Array[String] = Array("Mira", "Arun", "Zoya")
java.util.Arrays.sort(names)
println(java.util.Arrays.toString(names))
[Arun, Mira, Zoya]
When working with Java methods, verify the expected element type. For example, Array[Int] corresponds to a Java primitive int[], while Array[String] corresponds to String[].
Scala Array and List Differences
| Feature | Array | List |
|---|---|---|
| Size | Fixed after creation | New lists can be built by adding elements |
| Mutability | Elements are mutable | Standard Scala List is immutable |
| Indexed access | Fast direct access with array(index) | Accessing later positions requires traversal |
| Typical use | Fixed-size indexed data and Java interoperability | Immutable sequence processing and recursive operations |
Choose an array when the size is known and efficient indexed access or Java interoperability is needed. Choose a List when immutable sequence operations and frequent construction from the front are more appropriate.
Common Scala Array Mistakes
- Using an index equal to the length: the last valid index is
length - 1, notlength. - Expecting an array to resize: operations such as
:+return a new array; they do not extend the original array in place. - Using
varunnecessarily: an array reference can often be avaleven when its elements need to change. - Printing an array directly: use
mkStringorjava.util.Arrays.toStringfor readable output. - Assuming assignment creates a copy: assigning an array to another variable creates another reference to the same array.
- Using an array for frequent insertions: consider
ArrayBufferwhen the collection must grow or shrink repeatedly.
Scala Array Complete Example
The following program creates an array, updates an element, filters values, calculates a total, and prints the results.
object ScalaArrayExample {
def main(args: Array[String]): Unit = {
val marks = Array(72, 84, 65, 91, 78)
marks(2) = 70
val passingMarks = marks.filter(_ >= 75)
val total = marks.sum
val average = total.toDouble / marks.length
println(s"Marks: ${marks.mkString(", ")}")
println(s"Marks of 75 or more: ${passingMarks.mkString(", ")}")
println(s"Total: $total")
println(f"Average: $average%.2f")
}
}
Marks: 72, 84, 70, 91, 78
Marks of 75 or more: 84, 91, 78
Total: 395
Average: 79.00
Scala Array Frequently Asked Questions
Are Scala arrays mutable?
Yes. The length of an array is fixed, but an existing element can be replaced by assigning a new value to its index.
How do you find the length of an array in Scala?
Use array.length or array.size. Both return the number of elements in the array.
How do you append an element to a Scala array?
Use array :+ element and assign the returned array to a variable. The original array is not resized. For frequent appends, use ArrayBuffer.
How do you fill a Scala array with the same value?
Use Array.fill(size)(value). For example, Array.fill(5)(0) creates an integer array containing five zeros.
What is the difference between a Scala Array and List?
An Array has mutable elements, fixed length, and direct indexed access. A standard Scala List is immutable and is designed for linked-sequence operations rather than constant-time access by index.
Scala Array Editorial QA Checklist
- Confirm that every example uses zero-based indexing and does not access
array.lengthas an element index. - Verify that examples distinguish fixed array length from mutable array elements.
- Check that append examples explain that
:+,+:, and++create new arrays. - Confirm that output blocks match the values produced by the Scala code.
- Ensure multidimensional examples use the correct row-and-column access form, such as
matrix(row)(column). - Check that Java interoperability examples use compatible JVM array element types.
TutorialKart.com