Kotlin Array.reversed()

Kotlin Array.reversed() function

In Kotlin, the Array.reversed() function is used to get the elements of given array as a list in reversed order. It does not modify the original array.

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

Syntax

The syntax of the Array.reversed() function is

fun <T> Array<T>.reversed(): List<T>

The reversed() function does not take any parameters.

The reversed() function returns a List.

Examples for Array.reversed() function

1. Reversing an Array of Numbers

In this example, we’ll use reversed() to get the elements of a given array in reversed order as a list.

Kotlin Program

fun main() {
    val numbersArray = intArrayOf(1, 2, 3, 4, 5)

    // Reversing the array
    val result = numbersArray.reversed()

    // Printing given and reversed array
    println("Given Array\n${numbersArray.contentToString()}")
    println("Reversed\n[${result.joinToString(", ")}]")
}

Output

Given Array
[1, 2, 3, 4, 5]
Reversed
[5, 4, 3, 2, 1]

2. Reversing an Array of Strings

In this example, we’ll use reversed() to get the elements of a string array in reversed order.

Kotlin Program

fun main() {
    val fruitsArray = arrayOf("apple", "banana", "cherry")

    // Reversing the array
    val result = fruitsArray.reversed()

    // Printing given and reversed array
    println("Given Array\n${fruitsArray.contentToString()}")
    println("Reversed\n[${result.joinToString(", ")}]")
}

Output

Given Array
[apple, banana, cherry]
Reversed
[cherry, banana, apple]

Summary

In this tutorial, we’ve covered the reversed() function in Kotlin arrays, its syntax, and how to use it to get the elements of a given array in reversed order.