🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Arrays

An array is a collection that stores values of the same type in a fixed order. Each value sits at a numbered position, and the value at a position can be changed.

Create an array and read values by position

An array is created with Array and round brackets. A position in round brackets reads the value stored there.

@main def main(): Unit =
  val scores = Array(10, 20, 30)
  println(scores(0))
  println(scores(2))

Writing changes the value at a position

Placing a new value at a position replaces the old value there. The joined text shows the whole array after the change.

@main def main(): Unit =
  val scores = Array(50, 60, 70)
  scores(1) = 65
  println(scores(1))
  println(scores.mkString(", "))

Length counts the values in an array

The length tells how many values an array holds. mkString joins all the values into readable text.

@main def main(): Unit =
  val names = Array("Ana", "Bo", "Cy")
  println(names.length)
  println(names.mkString(", "))

Example

@main def main(): Unit =
  val prices = Array(5, 8, 12)
  prices(0) = 6
  println(prices.length)
  println(prices(0))
  println(prices.mkString(", "))

Key points

  • Creation: Array(10, 20, 30) creates an array that holds the three numbers in order.
  • Reading: numbers(0) reads the first value, because positions start at 0.
  • Writing: numbers(0) = 99 stores a new value at that position.
  • Length: numbers.length gives how many values the array holds.
  • Joining: numbers.mkString(", ") joins the values into one string with a separator between them.

In this example, the program creates an array of three prices and then changes the first price from 5 to 6. It prints the length, which is still 3, then prints the first value, and finally joins all the values to show the full array after the change.

Note

An array can change its values, but its length stays the same.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

A program creates val a = Array(4, 7, 9) and then runs a(1) = 10. What is a(1) after that line?