This article explores different ways to iterate through an array in reverse order in Kotlin.

1. Using reversed() function

In Kotlin, you can easily create ranges of values using the rangeTo() function and its operator form ... The idea is to create a range of array indices and reverse it using the reversed() function.

Download Code

 
You can shorten the code using the indices property, which returns the range of valid indices for the array.

Download Code

 
If the index is not needed, you can call the reversed() function on the array like:

Download Code

 
You can even start the loop at the last index of the array and use the downTo function with step -1.

Download Code

2. Using withIndex() function

Alternatively, you can use the withIndex() library function. It returns a lazy Iterable that wraps each element of the original array into an IndexedValue containing the index of that element and the element itself.

The following solution use withIndex() function together with reversed() to iterate through an array in reverse order.

Download Code

 
Following is the equivalent version using a for loop:

Download Code

3. Reverse Copy

You can even create a reverse copy of an array. The idea is to create a range of array indices and map the values of the original array in reverse order. Finally, accumulate the reversed elements into the corresponding array. This would translate to a simple code below:

Download Code

That’s all about iterating an array in reverse order in Kotlin.