Kotlin List asReversed()
Syntax & Examples


Syntax of List.asReversed()

The syntax of List.asReversed() extension function is:

fun <T> List<T>.asReversed(): List<T>

This asReversed() extension function of List returns a reversed read-only view of the original List. All changes made in the original list will be reflected in the reversed one.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing integers from 1 to 5.
  • We use the asReversed() function to get the reversed view of list1.
  • The reversedList contains elements in reverse order, i.e., [5, 4, 3, 2, 1].
  • We print the reversed list using println(reversedList).

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4, 5);
    val reversedList = list1.asReversed();
    println(reversedList);
}

Output

[5, 4, 3, 2, 1]

2 Example

In this example,

  • We create a list named list2 containing characters 'a' to 'd'.
  • We use the asReversed() function to get the reversed view of list2.
  • The reversedList contains characters in reverse order, i.e., ['d', 'c', 'b', 'a'].
  • We print the reversed list using println(reversedList).

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf('a', 'b', 'c', 'd');
    val reversedList = list2.asReversed();
    println(reversedList);
}

Output

[d, c, b, a]

3 Example

In this example,

  • We create a list named list3 containing strings "apple", "banana", and "cherry".
  • We use the asReversed() function to get the reversed view of list3.
  • The reversedList contains strings in reverse order, i.e., ["cherry", "banana", "apple"].
  • We print the reversed list using println(reversedList).

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf("apple", "banana", "cherry");
    val reversedList = list3.asReversed();
    println(reversedList);
}

Output

[cherry, banana, apple]

Summary

In this Kotlin tutorial, we learned about asReversed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.