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.
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.
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
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
syntaxWe 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
Often in Scala we use lists. With lists we have an immutable collection. With arrays, meanwhile, we can change elements.
With Array.ofDim
we create two-dimensional (up to five-dimensional) arrays in Scala. A type argument (to indicate element type) is needed.
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.