Suppose you have an array nums and your task is to increment every number in that array by one.
The first idea that might come to your mind is to write a for loop like this:
val nums = intArrayOf(1, 2, 3)
// Increment items:
for (num in nums) {
num++
}
// Print the array after:
for (num in nums) {
println(num)
}
but this code doesn't even compile. The compiler reports:
error: 'val' cannot be reassigned
In a Kotlin for loop, the loop variable num is read-only, like a val, so we can't do num++ on it. And even if we could, the change would not reach nums, as the next sections explain.
Let's talk about copies:
Take a look at this code:
val number = 100
var number_copy = number
number_copy++
println(number_copy) // Output: 101
println(number) // Output: 100
Although we wrote var number_copy = number, this doesn't mean that number and number_copy are one and the same.
number_copy is a completely different entity (stored at a different memory address) than number.
What we did is initialize this new number_copy entity with the value of number. That's why we say the number_copy is a copy of number.
And so number_copy++ will only increment number_copy and won't have any effect on number.
The loop variable is just a copy:
This is what also happens with a for loop.
Whenever you write a for loop, the loop variable (in our case num) is just a copy of the current item of the array, not the item itself.
This code
val nums = intArrayOf(1, 2, 3)
for (num in nums) {
num++
}
works exactly like this code:
val nums = intArrayOf(1, 2, 3)
var num = nums[0]
num++
num = nums[1]
num++
num = nums[2]
num++
Notice that only the variable num is being manipulated, which has nothing to do with the actual entries of the array nums.
You'll see this better if we copy each item into a variable we are allowed to change and print it on each iteration.
val nums = intArrayOf(1, 2, 3)
for (item in nums) {
var num = item
num++
println(num)
}
// Print the array after:
for (num in nums) {
println(num)
}
The output of this code is:
2
3
4
1
2
3
Looping over the indices:
In order to manipulate the entries of some array we have to loop over the items' indices:
val nums = intArrayOf(1, 2, 3)
for (index in 0 until nums.size) {
nums[index]++
}
This code works exactly like this one:
val nums = intArrayOf(1, 2, 3)
var index = 0
nums[index]++
index++
nums[index]++
index++
nums[index]++
In this way we directly manipulate the actual entries of the array (nums[0], nums[1], etc.)
Assignment:
Fix our code such that it correctly increments (adds one to) the even numbers of nums and decrements (subtracts one from) the odd ones.
Free plan: 30 tutor messages. PRO is unlimited.
