Kotlin List.asReversed() – Examples

Kotlin List.asReversed()

The Kotlin List.asReversed() function returns a reversed read-only view of the original List.

Syntax

List.asReversed()

Returns a reversed read-only view of the original List.

Note: Any changes made in the original list will be reflected in the reversed one.

Example 1

In this example,

  1. Take a list of elements.
  2. Call asReversed() function, and print the returned read-only list.

Program

fun main(args: Array<String>) {
    var list1 = listOf("a", "b", "c", "d")
    val reversed = list1.asReversed()
    println("Original list : $list1")
    println("Reversed list : $reversed")
}

Output

Original list : [a, b, c, d]
Reversed list : [d, c, b, a]

Example 2

In this example,

  1. Take a list of items.
  2. Call asReversed() and get reversed read-only list.
  3. Make changes to the original list.
  4. Observe the changes in the reversed list.

Program

fun main(args: Array<String>) {
    var list1 = mutableListOf("a", "b", "c", "d")
    val reversed = list1.asReversed()
    list1.add("e")
    println("Original list : $list1")
    println("Reversed list : $reversed")
}

Output

Original list : [a, b, c, d, e]
Reversed list : [e, d, c, b, a]