Array
An Array is a row of numbered boxes of a fixed size whose contents you can swap. It is like an egg carton where you can change the eggs but not add more slots.
In this page:
Syntax
val array = Array(value1, value2, value3)
val sized = new Array[Type](size)
array(index) = new_value
Array
A Scala Array is a fixed-size, mutable sequence backed directly by the JVM's native array type, offering fast indexed access.
Unlike List, individual elements of an Array can be reassigned after creation, though its length is fixed. Arrays are typically used when you need Java interop or maximum performance for indexed access.
Note:
Array elements can be mutated in place with
arr(i) = newValue, unlike the elements of an immutable List.Example: Array
object Main extends App {
val numbers = Array(10, 20, 30, 40)
println(numbers.length)
println(numbers(0))
numbers(1) = 99
println(numbers.mkString(", "))
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting an
Arrayto grow with+=, when its size is fixed and needs anArrayBuffer. - Accessing an index like
numbers(4)beyond the length, which throwsArrayIndexOutOfBoundsException. - Printing an array with
println(numbers)and getting something like[I@1b6d3586, when you neednumbers.mkString(", ").
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: