Kotlin报接收者类型不匹配无适用候选方法错误如何修复
错误原因
- 核心报错根源:你虽然给泛型T声明了上界
Number,但Kotlin的Number是抽象类,本身没有定义plus运算符方法(也就是+对应的重载方法)。Int、Double、Long等具体数值类型的相加能力是各自类单独实现的,泛型类型擦除后,编译器无法确认两个T类型的实例一定支持+操作,所以会抛出Unresolved reference. None of the following candidates is applicable because of receiver type mismatch的错误。 - 代码里还存在两个逻辑问题:
- 循环范围写为
0..list1.size是双闭区间,会访问到索引等于list1.size的元素,而List合法索引最大为size - 1,运行时会触发索引越界异常 - 你逻辑中往
res可变列表中添加计算结果,但函数最终返回的是新建的空列表listOf(),不会返回你计算得到的结果
- 循环范围写为
修复方案
根据你的使用场景选对应实现即可:
方案1:仅需支持Int类型列表求和
如果你的使用场景和示例一致,都是Int类型的列表,直接去掉泛型,明确指定参数类型即可,写法最简单:
fun main(){ val arg1 = listOf(1,2,3,4,5,6) val arg2 = listOf(2,3,4,5,6,7) println(sumLists(arg1, arg2)) // 输出 [3, 5, 7, 9, 11, 13] } fun sumLists(list1: List<Int>, list2: List<Int>): List<Int>?{ val res = mutableListOf<Int>() if (list1.size != list2.size) return null // 用until做左闭右开区间,避免越界 for (i in 0 until list1.size) res.add(list1[i] + list2[i]) return res // 返回实际计算的结果,不是空列表 }
方案2:需要兼容多种Number类型
如果要支持Int、Long、Double、Float等多种数值类型的列表求和,因为Number没有统一的plus实现,需要在函数内显式判断类型做对应计算:
fun main(){ val intList1 = listOf(1,2,3,4,5,6) val intList2 = listOf(2,3,4,5,6,7) println(sumLists(intList1, intList2)) // 输出 [3, 5, 7, 9, 11, 13] val doubleList1 = listOf(1.1, 2.2, 3.3) val doubleList2 = listOf(4.4, 5.5, 6.6) println(sumLists(doubleList1, doubleList2)) // 输出 [5.5, 7.7, 9.9] } fun <T: Number> sumLists(list1: List<T>, list2: List<T>): List<T>?{ val res = mutableListOf<T>() if (list1.size != list2.size) return null for (i in 0 until list1.size) { val a = list1[i] val b = list2[i] @Suppress("UNCHECKED_CAST") val sum = when(a) { is Int -> a + b.toInt() is Long -> a + b.toLong() is Float -> a + b.toFloat() is Double -> a + b.toDouble() is Short -> a + b.toShort() is Byte -> a + b.toByte() else -> throw IllegalArgumentException("不支持的数值类型") } as T res.add(sum) } return res }
内容的提问来源于stack exchange,提问作者GeoD
相关产品推荐
相关产品推荐

