Reputation: 429
I am trying to get the Maximum number between two numbers in Kotlin & I keep getting Type mismatch error. I tried using Int?.toInt() It didn't work.
I also tried to use Int!! as the double exclamation for None Null values, It didn't work too.
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)
}
Upvotes: 6
Views: 22598
Reputation: 39843
The arrayOfNulls()
function is declared as
fun <reified T> arrayOfNulls(size: Int): Array<T?>
Thus any item of sorted
might be null. So if you want to properly use it as null, just do a normal null check value != null
before using it.
Instead of using nulls, you could also use Int.MIN_VALUE
as initialization value.
val sorted = Array(nums.size) { MIN_VALUE }
Upvotes: 2