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

Kotlin. How to fix: None of following candidates is applicable because of receiver type mismatch

I am studying kotlin and have encountered this problem: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch.

fun main(){
    val arg1 = listOf(1,2,3,4,5,6)
    val arg2 = listOf(2,3,4,5,6,7)

    sumLists(arg1, arg2)
}

fun <T: Number> sumLists(list1: List<T>, list2: List<T>): List<T>?{
    val res = mutableListOf<T>()
    if (list1.size != list2.size)
        return null
    else {
        for (i in 0..list1.size)
            res.add(list1[i] + list2[i])
    }
    return listOf()
}

I don’t really understand why it doesn’t work because I wrote <T: Number>

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

>Solution :

There is no Number + Number operator defined in Kotlin, so the compiler can’t guarantee that T + T is possible. For example, you can create your own class MyNumber which extends Number, but doesn’t support add operation.

I believe there is no other way than write a separate code for each subtype of Number that you want to support:

for (i in 0 .. list1.lastIndex) {
    val item1 = list1[i]
    val item2 = list2[i]
    @Suppress("UNCHECKED_CAST")
    val result = when {
        item1 is Int && item2 is Int -> item1 + item2
        item1 is Float && item2 is Float -> item1 + item2
        ...
        else -> throw IllegalArgumentException()
    } as T
    res.add(result)
}

We have to do unchecked cast here, because the compiler is not smart enough to understand that the type of the result is T.

Also, I changed for-loop bounds to list1.lastIndex to fix the off-by-one bug.

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