I'm really new to kotlin and here I'm trying to reverse a list by defining a function without any returns. My logic is simply swapping indexes up to the middle.
However, I am getting an error message which I have attached below. I would appreciate it if anyone could help me understand the mistake. I have attached my code and error message below.
Reverse function
fun reverse (list: List<Int>){
var j = list.size-1
for (i in 0..(list.size-1)/2){
var t = list[i]
list[i] = list[j]
list[j] = t
j--
}
}
Main function
fun main() {
var list = listOf(1,2,3,4,5,6,7,8,9,10)
reverse(list)
println(list)
}
Error message
Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: (This is for the swapping line list[i] = list[j]
)
CodePudding user response:
You need a MutableList, you cannot change elements in a List.
fun reverse(list: MutableList<Int>) {
var j = list.size - 1
for (i in 0..(list.size - 1) / 2) {
val t = list[i]
list[i] = list[j]
list[j] = t
j--
}
}
var list = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
reverse(list)
println(list) // Output [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Also: there is a built-in function reversed(), see: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/reversed.html, which will return a List. And there is a built-in function asReversed(), see: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/as-reversed.html, which will return a MutableList.