Kotlin Array - reverse() Function



The Kotlin array reverse() function is used to reverse elements of an array in-place within a specified range.

This function reverses the elements within the specified range. If no range is specified, it reverses all the elements of an array.

Exception

Following are the exceptions −

  • IndexOutOfBoundsException − If fromIndex is less than zero or toIndex is greater than the size of this array.

  • IllegalArgumentException − If fromIndex is greater than toIndex.

Syntax

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

fun <T> Array<T>.reverse()
,or
fun <T> Array<T>.reverse(fromIndex: Int, toIndex: Int)

Parameters

This function accepts following parameters −

  • fromIndex − It represents start of the range (inclusive) to reverse.

  • toIndex − It represents end of the range (exclusive) to reverse.

Return value

The function returns an array or collection in the reverse order.

Example 1

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

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 2, 3, 4, 5)
   numbers.reverse()
   println("Reversed elements: ${numbers.joinToString(", ")}")
}

Output

The above code generate following output −

Reversed elements: 5, 4, 3, 2, 1

Example 2

This example, creates an array and reversing elements of this array in-place within the specified range −

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 2, 3, 4, 5)
   
   // specify the start and last index
   numbers.reverse(2, 5)
   println("Reversed elements: ${numbers.joinToString(", ")}")
}

Output

Following is the output −

Reversed elements: 1, 2, 5, 4, 3

Example 3

In the below example, use the reverse() function to check What will be the output if toIndex is greater than the size of an array −

fun main(args: Array<String>) {
   val numbers = arrayOf<String>("Hii", "This", "is", "tutorialspoint")
   
   // specify the start and last index
   numbers.reverse(2, 5)
   println("Reversed elements: ${numbers.joinToString(", ")}")
}

Output

The above code throw an exception if an toIndex is greater than size of array −

Exception in thread "main" java.lang.IndexOutOfBoundsException: fromIndex: 2, toIndex: 5, size: 4
kotlin_arrays.htm
Advertisements