Kotlin中IntArray调用mapIndexedNotNull出现接收器类型不匹配错误原因
报错原因解析:IntArray调用mapIndexedNotNull失败
核心问题
IntArray是Kotlin的基本数据类型数组,它并没有实现Iterable接口——而mapIndexedNotNull是定义在Iterable接口上的扩展函数,只能被实现了该接口的集合类(比如List、Set)调用。你的代码里用IntArray直接调用这个函数,就会触发「接收器类型不匹配」的报错,因为编译器找不到适用于IntArray的mapIndexedNotNull函数。
解决思路
要实现你想要的「收集非零元素的索引-值对」需求,有两种简单方式:
先把IntArray转为List
调用IntArray的toList()方法转成List<Int>,就可以正常使用mapIndexedNotNull了:val nums: IntArray = intArrayOf(1, 0, 3, 0, 5) val positionValuePairs: List<Pair<Int, Int>> init { positionValuePairs = nums.toList().mapIndexedNotNull { index, value -> if (value != 0) index to value else null } }手动遍历过滤
用forEachIndexed遍历数组,手动收集符合条件的Pair:val nums: IntArray = intArrayOf(1, 0, 3, 0, 5) val positionValuePairs: List<Pair<Int, Int>> init { val tempPairs = mutableListOf<Pair<Int, Int>>() nums.forEachIndexed { index, value -> if (value != 0) { tempPairs.add(index to value) } } positionValuePairs = tempPairs }
内容的提问来源于stack exchange,提问作者HukeLau_DABA
相关产品推荐
相关产品推荐

