Kotlin Array - reversed() Function



The Kotlin array reversed() function is used to reverse elements of an array and return a list containing all elements in reverse order.

For example, arrayOf(1,2,3).reversed() is equal to [3, 2, 1]

Syntax

Following is the syntax of Kotlin array reversed() function −

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

Parameters

This function does not accepts any parameters −

Return value

The function returns a list.

Example 1

The following is a basic example to demonstrate the use of reversed() function −

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 2, 3, 4, 5)
   val res = numbers.reversed()
   println("list: $res")
}

Output

The above code generate following output −

list: [5, 4, 3, 2, 1]

Example 2

Now, Let's creates an array that stores string value. We then use the reversed() function to return a list containing reverse string.

fun main(args: Array<String>) {
   val strings = arrayOf<String>("This", "is", "tutorialspoint", "India")
   val res = strings.reversed()
   println("list: $res")
}

Output

Following is the output −

list: [India, tutorialspoint, is, This]

Example 3

The below example uses reversed() function to return a list containing elements of set in revered order −

fun main(args: Array<String>){
   val set = hashSetOf<Int>(1, 2, 3, 4, 5, 6)
   val revSet = set.reversed();
   println("reversed set: $revSet")
}

Output

The above code produced following output −

reversed set: [6, 5, 4, 3, 2, 1]
kotlin_arrays.htm
Advertisements