You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中IntArray调用mapIndexedNotNull出现接收器类型不匹配错误原因

报错原因解析:IntArray调用mapIndexedNotNull失败

核心问题

IntArray是Kotlin的基本数据类型数组,它并没有实现Iterable接口——而mapIndexedNotNull是定义在Iterable接口上的扩展函数,只能被实现了该接口的集合类(比如List、Set)调用。你的代码里用IntArray直接调用这个函数,就会触发「接收器类型不匹配」的报错,因为编译器找不到适用于IntArray的mapIndexedNotNull函数。

解决思路

要实现你想要的「收集非零元素的索引-值对」需求,有两种简单方式:

  1. 先把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
        }
    }
    
  2. 手动遍历过滤
    用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:11:04