arrays - Kotlin 类型不匹配 : inferred type is Int? 但预期为 Int

标签 arrays kotlin

我试图在 Kotlin 中获得两个数字之间的最大数字,并且我不断收到类型不匹配错误。我尝试使用 Int?.toInt() 它没有用。

我也试过用 Int!!作为 None Null 值的双感叹号,它也不起作用。

fun main(args: Array<String>){

    val nums = arrayOf(8, 5, 6, 8, 9)
    var sorted = arrayOfNulls<Int>(nums.size)

    // manually set 2 values
    sorted[0] = nums[0]
    sorted[1] = nums[1]

    for(i in 1 until nums.size-1){
        val value = sorted[i - 1]
        val max = maxOf(value!!, nums[i]) // This line throws Null pointer exception: error: type mismatch: inferred type is Int? but Int was expected
        // do something with max
    }

    println(sorted)
}

最佳答案

arrayOfNulls() 函数声明为

fun <reified T> arrayOfNulls(size: Int): Array<T?>

因此 sorted 的任何项目可能为空。所以如果你想正确地使用它作为空值,只需做一个正常的空值检查 value != null在使用它之前。

除了使用空值,您还可以使用 Int.MIN_VALUE作为初始化值。
val sorted = Array(nums.size) { MIN_VALUE }

关于arrays - Kotlin 类型不匹配 : inferred type is Int? 但预期为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664688/

相关文章:

android - 没有 Firebase 对象的 setter/getter

android - 如何从文本按钮中删除填充?

Android - Kotlin : make GET or PUT request sending JWT

php - CodeIgniter - 数据库结果数组,但只有一行

python - 根据符号将数组中列的元素归一化为 1 或 -1

arrays - 从值范围内的 influxdb 记录中选择

python - 从文本文件读取数据到python中的numpy数组中

arrays - 如何为 Array 自定义 toString?

android - 为什么 Intent 中的类有 "::class.java"后缀?

android - StateFlow 设置值会丢弃一些事件,但更新不会