Kotin 类型不匹配:推断类型是 Int?但 Int 是预期的

tru*_*yer 6 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)
}
Run Code Online (Sandbox Code Playgroud)

tyn*_*ynn 2

arrayOfNulls()函数声明为

fun <reified T> arrayOfNulls(size: Int): Array<T?>
Run Code Online (Sandbox Code Playgroud)

因此 的任何一项都sorted可能为空。因此,如果您想正确地将其用作 null,只需value != null在使用它之前进行正常的 null 检查即可。

除了使用空值之外,您还可以将其用作Int.MIN_VALUE初始化值。

val sorted = Array(nums.size) { MIN_VALUE }
Run Code Online (Sandbox Code Playgroud)