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,
- Take a list of elements.
- 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,
- Take a list of items.
- Call asReversed() and get reversed read-only list.
- Make changes to the original list.
- 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]