Does anyone know how to use swap() method now sn kotlin? Because it shows me an error that there is no such method.
Tried to copy this code in mine. Saw a lot of examples how to rewrite this, but this is an exercise on how to search mistakes (here it is in the size of the list and if loop), but now instead of one mistake that i need i have 2
Updated by moderator:
Author of the question provided this code in the comment:
fun main() {
val list = listOf(5, 3, 6, 7, 9, 1)
sortlist(list)
println(list)
}
private fun sortlist(list: List<Int>) {
for (i in 0..list.size -1) {
for(j in 0.. list.size - 2) {
if (list[j] > list[j + 1] ) {
Collection.swap(list, j, j + 1)
}
}
}
}
2
Answers
Apparently, you made a mistake when copying the code. In the original code included in the image, the function name was:
Collections.swap()
which is the correct name. In the code you provided in the comments it is:Collection.swap()
. You miss a letter "s" and this is probably the cause of your problem.method requires the mutable list in order to swap it’s elements. Make sure you provide the mutable list to this method. As per your code, it’s looking you are passing immutable list.