Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading