asReversed

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

Returns a reversed read-only view of the original List. All changes made in the original list will be reflected in the reversed one.

Samples

import samples.*
fun main() { 
   //sampleStart 
   val original = mutableListOf('a', 'b', 'c', 'd', 'e')
val originalReadOnly = original as List<Char>
val reversed = originalReadOnly.asReversed()

assertPrints(original, "[a, b, c, d, e]")
assertPrints(reversed, "[e, d, c, b, a]")

// changing the original list affects its reversed view
original.add('f')
assertPrints(original, "[a, b, c, d, e, f]")
assertPrints(reversed, "[f, e, d, c, b, a]")

original[original.lastIndex] = 'z'
assertPrints(original, "[a, b, c, d, e, z]")
assertPrints(reversed, "[z, e, d, c, b, a]") 
   //sampleEnd
}

@JvmName(name = "asReversedMutable")
fun <T> MutableList<T>.asReversed(): MutableList<T>

Returns a reversed mutable view of the original mutable List. All changes made in the original list will be reflected in the reversed one and vice versa.

Samples

import samples.*
fun main() { 
   //sampleStart 
   val original = mutableListOf(1, 2, 3, 4, 5)
val reversed = original.asReversed()

assertPrints(original, "[1, 2, 3, 4, 5]")
assertPrints(reversed, "[5, 4, 3, 2, 1]")

// changing the reversed view affects the original list
reversed.add(0)
assertPrints(original, "[0, 1, 2, 3, 4, 5]")
assertPrints(reversed, "[5, 4, 3, 2, 1, 0]")

// changing the original list affects its reversed view
original[2] = -original[2]
assertPrints(original, "[0, 1, -2, 3, 4, 5]")
assertPrints(reversed, "[5, 4, 3, -2, 1, 0]") 
   //sampleEnd
}