I'm using a HashMap<Int, Int>
in Kotlin and when I get
out of it the return type is Int?
.
How can I convert the Int?
to an Int
?
So far I've tried using Int?.toInt()
, but that seems to be returning an Int?
.
I'm writing a Fibonacci function, and my code looks like:
val fibMemo : Map<Int, Int> = HashMap<Int,Int>() fun fibN(n:Int) : Int { if (n == 0 || n == 1) return 1 if (fibMemo.containsKey(n)) // Error here: Type mismatch: inferred type is Int? but Int was expected return fibMemo.get(n)?.toInt() else { val newNum : Int = fibN(n-1) + fibN(n-2) fibMemo.put(n, newNum) return newNum } }
Converts this Int value to Double. The resulting Double value represents the same numerical value as this Int .
Converts this Int value to Float. The resulting value is the closest Float to this Int value. In case when this Int value is exactly between two Float s, the one with zero at least significant bit of mantissa is selected.
The direct answer, use the !!
operator to assert that you trust a value is NOT null and therefore changing its type to the non null equivalent. A simple sample showing the assertion allowing the conversion (which applies to any nullable type, not just Int?
)
val nullableInt: Int? = 1 val nonNullableInt: Int = nullableInt!! // asserting and smart cast
Another way to convert a value is via a null check. Not useful in your code above, but in other code (see Checking for null in conditions):
val nullableInt: Int? = 1 if (nullableInt != null) { // allowed if nullableInt could not have changed since the null check val nonNullableInt: Int = nullableInt }
This questions is also answered by the idiomatic treatment of nullability question: In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With