Arrays are mutable
You can change the elements of an array after it is created. Use the same bracket notation you use for reading, but put it on the left of an assignment:
val ourArray = intArrayOf(50, 40, 30)
ourArray[0] = 15
ourArray[1] = -1
println(ourArray.contentToString())
[15, -1, 30]
The assignment replaces the value stored at that index. The size doesn't change, and the other elements stay as they were: index 2 still holds 30. This is different from a String, which you can't modify in place.
Compound assignment
When the new value is based on the old one, use a compound operator such as +=. The line ourArray[2] += 5 reads the element, adds 5 and stores the result back at the same index, exactly as ourArray[2] = ourArray[2] + 5 would. The operators -=, *=, /= and %= work the same way.
val and the contents
The arrays above are declared with val, yet their elements change. val means the variable can't be pointed at another array, so ourArray = intArrayOf(1) doesn't compile (the compiler reports that a val cannot be reassigned). It says nothing about what is inside the array.
Why updating is cheap
Assigning to an index replaces one slot and touches nothing else, however big the array is. Updating the element at index 0 costs the same as updating the one at index 1,000. This fixed cost is one of the main reasons arrays are used for large collections of numbers.
Two names, one array
If two variables refer to the same array, an update through one is visible through the other. After val b = ages, the statement b[0] = 1 also changes ages[0]. Call ages.copyOf() when you want a separate array to change.
The exercise
The starter code:
val fruits = arrayOf("mango", "kiwi", "grapefruit")
val ages = intArrayOf(14, 32, 50, 21)
- Replace the first fruit. The first item is at index 0, so assign
"apple"tofruits[0]. The array becomes[apple, kiwi, grapefruit]. - Add 5 to the second age. The second item is at index 1. The line
ages[1] += 5turns 32 into 37, giving[14, 37, 50, 21].
val fruits = arrayOf("mango", "kiwi", "grapefruit")
val ages = intArrayOf(14, 32, 50, 21)
fruits[0] = "apple"
ages[1] += 5
This code prints nothing. To see the result, add println(fruits.contentToString()) and println(ages.contentToString()), which print [apple, kiwi, grapefruit] and [14, 37, 50, 21].
Types stay fixed
An update can change a value but never a type. An IntArray always holds Int values, and an Array<String> always holds strings. If you assign a value of another type, the compiler reports an error before the program runs. That is a safety net: you can't turn one slot of a numbers array into text by accident.
Checking your update
Because the lesson's code prints nothing, it is easy to wonder whether an update happened. Print the array after the change with contentToString(), or print one element by index. Seeing [14, 37, 50, 21] confirms that only the element at index 1 changed and that the other three kept their values. Printing before and after the update is a simple way to understand any array code you meet.
Common mistakes
- Wrong index.
fruits[1] = "apple"replaceskiwi, the second item. The first item is at index 0. - Assigning the wrong type. An
IntArrayonly holds integers, soages[1] = "five"doesn't compile. - Assigning past the end.
ages[4] = 1on a four-element array throwsArrayIndexOutOfBoundsException. An array never grows to make room. - Replacing instead of adding.
ages[1] = 5sets the element to 5. To add 5 to what is there, use+=.
Updating in a loop
Assignment by index is what lets a loop change every element. This loop doubles each age in place:
val ages = intArrayOf(14, 32, 50, 21)
for (i in ages.indices) {
ages[i] *= 2
}
println(ages.contentToString())
[28, 64, 100, 42]
The loop needs the index, because assigning to a loop variable that holds a copy of an element wouldn't change the array.
Swapping two elements
To exchange two positions, save one value in a temporary variable first. Without it, the first assignment overwrites a value you still need:
val t = ages[0]
ages[0] = ages[3]
ages[3] = t
println(ages.contentToString())
[42, 64, 100, 28]
Key takeaways
array[i] = valuereplaces the element at indexi.array[i] += nupdates an element based on its current value.valprotects the variable, not the elements.- Assignment can't add new positions: the size stays fixed.