asReversed() vs reversed() in Kotlin?

As per the document

1. reversed()

It only returns a list (List<>) with elements in reversed order.

There are multiple definitions of this extension on different Objects like Array, List, etc.

Example of extension on

Array<>

/**
 * Returns a list with elements in reversed order.
 */
public fun <T> Array<out T>.reversed(): List<T> {
    if (isEmpty()) return emptyList()
    val list = toMutableList()
    list.reverse()
    return list
}

List<>

/**
 * Returns a list with elements in reversed order.
 */
public fun <T> Iterable<T>.reversed(): List<T> {
    if (this is Collection && size <= 1) return toList()
    val list = toMutableList()
    list.reverse()
    return list
}

2. asReversed()

It is only applicable to List<> and returns a reversed read-only view of the original List. All changes made in the original list will be reflected in the reversed one.


In Kotlin, both reversed and asReversed have their own unique functions.

The Reverse function returns a list with elements in reversed: order.

Reversed Function

Whereas, the asReversed function returns a reversed read-only view of the original List i.e., all changes made in the original list will be reflected in the reversed one.

asReversed Function

The difference between the two are that once the asReversed() function has been used, any changes in the original list will be reflected in the reversed list as well. But the same doesn't hold valid or true when the reversed() function is being used. It's merely used to reverse a list.

Example:

    val list = mutableListOf(0, 1, 2, 3, 4, 5)

    val asReversed = list.asReversed()
    val reversed   = list.reversed()

    println("Original list: $list")
    println("asReversed:    $asReversed")
    println("reversed:      $reversed")

    list[0] = 10

    println("Original list: $list")
    println("asReversed:    $asReversed")
    println("reversed:      $reversed")

Outputs

Original list: [0, 1, 2, 3, 4, 5]
asReversed:    [5, 4, 3, 2, 1, 0]
reversed:      [5, 4, 3, 2, 1, 0]
Original list: [10, 1, 2, 3, 4, 5]
asReversed:    [5, 4, 3, 2, 1, 10]
reversed:      [5, 4, 3, 2, 1, 0]

Try it online!

Tags:

Kotlin