Convert a nullable Int (Int?) to an Int in Kotlin
This article explores different ways to convert a nullable Int (Int?) to an Int in Kotlin.
1. Using !! operator
The not-null assertion operator (!!) asserts that the receiver expression is not equal to null. It converts any value to a non-null type and throws NullPointerException if the value is null. You can use it to convert an Int? to an Int, as shown below:
|
1 2 3 4 5 6 |
fun main() { val nullableInt: Int? = 10 val notNullableInt: Int = nullableInt!! print(notNullableInt) } |
2. Using Elvis Operator
Instead of throwing a NullPointerException when the value is null, you can return a default value with an Elvis operator (?:). If the expression to the left of ?: is not null, the Elvis operator returns it; otherwise, it returns the expression to the right.
|
1 2 3 4 5 6 |
fun main() { val nullableInt: Int? = null val notNullableInt: Int = nullableInt ?: 0 print(notNullableInt) } |
3. Performing Null Check
Alternatively, you can perform an explicit null check on the Int? value and assign a default value when the value is null.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val nullableInt: Int? = null var notNullableInt: Int = 0 // default value if (nullableInt != null) { notNullableInt = nullableInt } print(notNullableInt) } |
You can also throw NPE if the value is null.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val nullableInt: Int? = 10 if (nullableInt != null) { val notNullableInt: Int = nullableInt print(notNullableInt) } else { throw NullPointerException() } } |
That’s all about converting a nullable Int to an Int in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)