Home
Scala
Array Examples
Updated Dec 13, 2023
Dot Net Perls
Array. An array in Scala 3.3 has elements—it has strings like "tree" and "bird." And these can be updated. We can change the "bird" into a "flower."
With mutable elements, arrays provide an important ability to our linear collections in Scala. A list is immutable, but with arrays we can change elements.
An example. Here we create a 4-element Int array. With val we make the "numbers" variable so it cannot be reassigned. But the array elements are still mutable.
Info Apply() gets the value of an element from the array. We pass the index of the element. In an array this starts at 0.
object Program { def main(args: Array[String]): Unit = { // An array of four Ints. val numbers = Array(10, 20, 30, 40) // Get first number in array with apply. val first = numbers.apply(0) println(first) // Get last number. val last = numbers.apply(numbers.length - 1) println(last) } }
10 40
Update. This modifies an element in an array. The first argument is the index of the element. And the second argument is the new value of the element.
object Program { def main(args: Array[String]): Unit = { // An array of three strings. val plants = Array("tree", "moss", "fern") // Update first element to be a new string. plants.update(0, "flower") // Display array. plants.foreach(println(_)) } }
flower moss fern
Short syntax. We can apply and update elements in an array with an index. This is a shorthand syntax for apply and update. Here we get and change the first element.
object Program { def main(args: Array[String]): Unit = { val codes = Array(5, 10, 15) // Get first element. val first = codes(0) println(first) // Update first element. codes(0) = 50 // Get first element again. println(codes(0)) } }
5 50
Convert to Array. Often in Scala we use lists. With lists we have an immutable collection. With arrays, meanwhile, we can change elements.
Convert
Two dimensions. With Array.ofDim we create two-dimensional (up to five-dimensional) arrays in Scala. A type argument (to indicate element type) is needed.
2D List
Unlike lists, arrays are mutable. We can use update to change their elements. Arrays can be used in a similar way to lists. They store elements of a single type in a linear order.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen