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.
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.
// An array of four Ints.val numbers = Array(10, 20, 30, 40)
// Get first number in array with apply.
val first = numbers.apply(0)
// Get last number.
val last = numbers.apply(numbers.length - 1)
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.
// An array of three strings.
val plants = Array("tree", "moss", "fern")
// Update first element to be a new string.
// Display array.
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.
val codes = Array(5, 10, 15)
// Get first element.
val first = codes(0)
// Update first element.
codes(0) = 50
// Get first element again.
Convert to Array. Often in Scala we use lists. With lists we have an immutable collection. With arrays, meanwhile, we can change elements.