now i'm trying to make reversed for a loop.The simple way of reverse for is for(i in start downTo end)
but,what if I use array as a start/end point?
To reverse a given string in Kotlin, call reversed() method on this String. reversed() returns a new String with the characters of the original string reversed in order.
To loop through an array backward using the forEach method, we have to reverse the array. To avoid modifying the original array, first create a copy of the array, reverse the copy, and then use forEach on it. The array copy can be done using slicing or ES6 Spread operator.
You can loop from the last index calculated by taking size - 1
to 0 like so:
for (i in array.size - 1 downTo 0) {
println(array[i])
}
Even simpler, using the lastIndex
extension property:
for (i in array.lastIndex downTo 0) {
println(array[i])
}
Or you could take the indices
range and reverse it:
for (i in array.indices.reversed()) {
println(array[i])
}
Additionally to the first answer from zsmb13, some other variants.
Using IntProgression.reversed
:
for (i in (0..array.lastIndex).reversed())
println("On index $i the value is ${array[i]}")
or using withIndex()
together with reversed()
array.withIndex()
.reversed()
.forEach{ println("On index ${it.index} the value is ${it.value}")}
or the same using a for loop:
for (elem in array.withIndex().reversed())
println("On index ${elem.index} the value is ${elem.value}")
or if the index is not needed
for (value in array.reversed())
println(value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With