C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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
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