← Back to Scala Course | Chapter 6: Collections Basics | Lesson 3 of 8

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:

  1. Array
Syntax
scala
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

markup
object Main extends App {
  val numbers = Array(10, 20, 30, 40)

  println(numbers.length)
  println(numbers(0))

  numbers(1) = 99
  println(numbers.mkString(", "))
}
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
  1. Expecting an Array to grow with +=, when its size is fixed and needs an ArrayBuffer.
  2. Accessing an index like numbers(4) beyond the length, which throws ArrayIndexOutOfBoundsException.
  3. Printing an array with println(numbers) and getting something like [I@1b6d3586, when you need numbers.mkString(", ").
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.