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

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


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? = 1val 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? = 1if (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


In order to convert an Int? to an Int use the sure() method.

The offending line should look like:

return fibMemo.get(n).sure()

Call to method sure() is Kotlin way (soon to be replaced by special language construct) to ensure non-nullability. As Java has not notation of nullable and non-nullable types we need to take some care on integration point. Please read amazing story of null-safety in Kotlin documentation.

source

Warning: the above information doesn't hold anymore. sure has been replaced by !!. See: http://blog.jetbrains.com/kotlin/migrating-sure/


You can also use a default value in null case:

val int: Int val nullableInt: Int? = null int = nullableInt ?: 0