Kotlin 无法获得所需的类型干扰 Array<Uri>!找到数组<Uri?>

Kotlin not able to get type interference required Array<Uri>! found Array<Uri?>

我正在尝试使用 uriArray 来解析图像路径,但卡在了 kotlin 的某一点上,它给我带来了问题 Array! found 数组

 val uriArray = arrayOfNulls<Uri>(imageList.size)
                    for (i in imageList.indices) {
                        val imgaesModel = imageList.get(i)
                        uriArray[i] = Uri.parse("file:" + imgaesModel.getPath())
                    }
                    mFilePathCallback!!.onReceiveValue(uriArray)
           // Above line is giving error 

请给我一些建议,因为我是 Kotlin 的新手,不胜感激。

由于您使用的是 arrayOfNulls,您的 uriArray 包含 Uri? (可为空的 Uri)元素。因为 onReceiveValue 不能接收预期的类型,它是一个 Uri 数组,而是接收一个 Uri? 数组。我的建议是不要创建 arrayOfNulls,而是使用 kotlin 中的 map 函数将 imageList 转换为 Uri 列表,然后将该列表转换为数组并使用它。

我觉得应该是这样的吧

val uriList = imagesList.map {
    Uri.parse("file:" + it.getPath())
}
val uriArray = uriList.toTypedArray() // something like this just convert list to array :)
mFilePathCallback!!.onReceiveValue(uriArray)

tasoluko 的替代答案是

val uriArray = Array<Uri>(imageList.size) { i ->
    val imagesModel = imageList[i] // get method can be written as indexing
    Uri.parse("file:" + imagesModel.path) // instead of getPath()
}