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>
CodePudding user response:
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.