Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

<< Back to SCALA

Scala Array Examples: Apply and Update

Use an Array and accesses elements with apply. Invoke update and clone.
Array. An array 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.

Apply: This method gets the value of an element from the array. We pass the index of the element. In an array this starts at 0.

Scala program that uses Array, apply // 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) Output 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.
Scala program that uses update // 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(_)) Output flower moss fern
Short syntax. We can apply and update elements in an array with an index. This is a short hand syntax for apply and update. Here we get and change the first element.
Scala program that uses short array syntax 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)) Output 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, 2D Array
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.
The Dev Codes