我试图在 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/