1. Overview

In Kotlin, nullability is a fundamental aspect of the language’s type system that helps prevent common NullPointerExceptions. Unlike many programming languages, Kotlin makes a clear distinction between nullable and non-nullable types, ensuring that null values are handled explicitly.

To take advantage of this null-safe type system, we need to designate nullable fields and variables by appending a question mark after their type. In this short tutorial, we’ll learn to extract the value of a nullable variable. Specifically, we’ll see how to convert a nullable Int? to an Int.

2. Not-Null Assertion Operator

The straight-forward solution for extracting a value from a nullable variable is to use the “not-null assertion” operator, also known as double-bang (!!) :

val value: Int? = 10
assertEquals(10, value!!)

As the name implies, this operator represents an assertion. Therefore, if the value isn’t present, a NullPointerException is thrown:

val value: Int? = null
assertFailsWith<NullPointerException> (
    block = { value!! }
)

 3. Elvis Operator

Alternatively, we can use the so-called “Elvis” operator to provide a default value when converting the Int? variable to a non-null Int.

The Elvis operator consists of a shorthand expression denoted by “?:“, followed by a default value:

val value: Int? = null
assertEquals(0, value ?: 0)

Needless to say, if value is non-null in the first place, the default value is simply ignored:

val value: Int? = 10
assertEquals(10, value ?: 0)

4. Conclusion

In this short article, we explored two different ways of extracting the numeric value of a nullable Int? variable. Initially, we saw the “double-bang” operator, which allows us to confidently extract a non-null value from a field or throw an exception if null. Subsequently, we explored a safer alternative using the “Elvis” operator to provide a default value.

As always, the complete code for this article is available over on GitHub.