How to Reverse List in Kotlin: Simple Syntax and Examples
In Kotlin, you can reverse a list using the
reversed() function which returns a new list with elements in reverse order. To reverse a mutable list in place, use reverse() which modifies the original list.Syntax
The reversed() function returns a new list with elements reversed without changing the original list. The reverse() function modifies the original mutable list in place.
list.reversed(): returns a new reversed listmutableList.reverse(): reverses the list in place
kotlin
val list = listOf(1, 2, 3, 4) val reversedList = list.reversed() val mutableList = mutableListOf(1, 2, 3, 4) mutableList.reverse()
Example
This example shows how to reverse an immutable list using reversed() and how to reverse a mutable list in place using reverse().
kotlin
fun main() {
val list = listOf("a", "b", "c", "d")
val reversedList = list.reversed()
println("Original list: $list")
println("Reversed list (new list): $reversedList")
val mutableList = mutableListOf("a", "b", "c", "d")
mutableList.reverse()
println("Mutable list after reverse(): $mutableList")
}Output
Original list: [a, b, c, d]
Reversed list (new list): [d, c, b, a]
Mutable list after reverse(): [d, c, b, a]
Common Pitfalls
A common mistake is expecting reversed() to change the original list. It does not; it returns a new reversed list. Also, reverse() only works on mutable lists and modifies the list in place, so it returns Unit (no value).
kotlin
fun main() {
val list = listOf(1, 2, 3)
list.reversed() // returns new list but original list stays the same
println(list) // prints [1, 2, 3]
val mutableList = mutableListOf(1, 2, 3)
val result = mutableList.reverse() // reverse() returns Unit
println(result) // prints kotlin.Unit
println(mutableList) // prints [3, 2, 1]
}Output
[1, 2, 3]
kotlin.Unit
[3, 2, 1]
Quick Reference
| Function | Description | Modifies Original List? |
|---|---|---|
| reversed() | Returns a new list with elements reversed | No |
| reverse() | Reverses a mutable list in place | Yes |
Key Takeaways
Use
reversed() to get a new reversed list without changing the original.Use
reverse() to reverse a mutable list in place.reverse() returns no value; it modifies the list directly.Immutable lists cannot be reversed in place; use
reversed() instead.Remember that
reversed() does not change the original list.