Kotlin Array.reverse()

Kotlin Array.reverse() function

In Kotlin, the Array.reverse() function is used to reverse the order of elements in the given array. It modifies the original array in-place, resulting in the elements being arranged in the opposite order.

In this tutorial, we’ll explore the syntax of the Array.reverse() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.reverse() function is

fun <T> Array<T>.reverse()

The reverse() function does not take any parameters.

The reverse() function does not return any value.

Examples for Array.reverse() function

1. Reversing an Array of Numbers

In this example, we’ll use reverse() to reverse the order of elements in an array of numbers.

Kotlin Program

fun main() {
    val numbersArray = intArrayOf(1, 2, 3, 4, 5)
    println("Given Array\n${numbersArray.contentToString()}")

    // Reversing the array
    numbersArray.reverse()

    // Printing the reversed array
    println("Array after reversal\n${numbersArray.contentToString()}")
}

Output

Given Array
[1, 2, 3, 4, 5]
Array after reversal
[5, 4, 3, 2, 1]

2. Reversing an Array of Strings

In this example, we’ll use reverse() to reverse the order of elements in an array of strings.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("apple", "banana", "cherry")
    println("Given Array\n${fruitsArray.contentToString()}")

    // Reversing the array
    fruitsArray.reverse()

    // Printing the reversed array
    println("Array after reversal\n${fruitsArray.contentToString()}")
}

Output

Given Array
[apple, banana, cherry]
Array after reversal
[cherry, banana, apple]

Summary

In this tutorial, we’ve covered the reverse() function in Kotlin arrays, its syntax, and how to use it to reverse the order of elements within an array.

Keep in mind that this function modifies the original array in-place, so use it when you want to change the order of elements directly within the existing array.