Kotlin Array.reversedArray() function
In Kotlin, the reversedArray()
function is used to create a new array with elements in the reverse order of the original array.
Unlike the Array.reversed() function, which returns a List, Array.reversedArray()
returns an Array with the elements from the original array in reversed order.
In this tutorial, we’ll explore the syntax of the Array.reversedArray()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.reversedArray()
function is:
fun <T> Array<out T>.reversedArray(): Array<T>
The reversedArray()
function returns a new Array with the reversed elements.
Examples for Array.reversedArray() function
1. Creating a Reversed Array of Numbers
In this example, we’ll use reversedArray()
to create a new array with the elements of an array of numbers in reverse order.
Kotlin Program
fun main() {
val numbersArray = intArrayOf(1, 2, 3, 4, 5)
// Creating a reversed array of numbers
val reversedNumbersArray = numbersArray.reversedArray()
// Printing the original and reversed arrays
println("Original Array\n${numbersArray.contentToString()}")
println("Reversed Array\n${reversedNumbersArray.contentToString()}")
}
Output
Original Array
[1, 2, 3, 4, 5]
Reversed Array
[5, 4, 3, 2, 1]
2. Creating a Reversed Array of Strings
In this example, we’ll use reversedArray()
to create a new array with the elements of an array of strings in reverse order.
Kotlin Program
fun main() {
val wordsArray = arrayOf("apple", "banana", "kiwi", "mango")
// Creating a reversed array of strings
val reversedNumbersArray = wordsArray.reversedArray()
// Printing the original and reversed arrays
println("Original Array\n${wordsArray.contentToString()}")
println("Reversed Array\n${reversedNumbersArray.contentToString()}")
}
Output
Original Array
[apple, banana, kiwi, mango]
Reversed Array
[mango, kiwi, banana, apple]
Summary
In this tutorial, we’ve covered the Array.reversedArray()
function in Kotlin, its syntax, and how to use it to create a new array with elements in the reverse order of the original array.