Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Kotlin How Can I Convert an Int? to an Int

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     } } 
like image 637
jjnguy Avatar asked Mar 05 '12 06:03

jjnguy


People also ask

How do you convert int to double in Kotlin?

Converts this Int value to Double. The resulting Double value represents the same numerical value as this Int .

How do I change an int to a float in Kotlin?

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.


1 Answers

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

like image 92
4 revs, 2 users 97% Avatar answered Sep 22 '22 14:09

4 revs, 2 users 97%