1. Overview
In Kotlin, nullability is a type system feature that can help us to avoid NullPointerExceptions.
In this quick tutorial, we’re going to introduce the not-null assertion (!!) operator and see how and when we should use it.
2. Not-Null Assertion
Each type in Kotlin has one nullable form and another non-nullable form. For instance, the Int type can hold non-null 32-bit integers. In addition to the same values, the Int? type can hold null values, too.
Kotlin provides many options to facilitate working with nullable data types in a safe manner.
However, sometimes we need to convert a nullable type to its non-nullable form forcibly. As it turns out, Kotlin’s not-null assertion operator !! does just that:
val answer: String? = "42"
assertEquals(42, answer!!.toInt())
Because we’re sure the answer is not null, we can use the !! operator. Otherwise, we couldn’t call the toInt method.
If we apply this operator on a null value, Kotlin will throw an instance of java.lang.NullPointerException:
@Test
fun givenNullableValue_WhenIsNull_ThenShouldThrow() {
assertFailsWith<NullPointerException> {
val noAnswer: String? = null
noAnswer!!
}
}
Also, if we apply !! to a non-nullable type, the compiler will still compile the code:
val answer = "42"
answer!!.toInt()
However, it will complain, giving us a warning message:
Unnecessary non-null assertion (!!) on a non-null receiver of type String
3. Use Cases
Most of the time, we shouldn’t apply the !! operator in pure Kotlin code. It’s better to use other and safer options such as null-safe calls or the Elvis operator.
However, while working with some third-party libraries, we may have to use this operator anyway. For example, let’s say we’re using bean validation annotations on a Spring DTO:
data class NewUserDto(
@get:NotNull
val username: String? = null
)
Spring automatically applies the validation rules to the request data. Therefore, after the validation is done, we’re sure that the username is not null:
val request: NewUserDto = // from controller
userService.registerUser(request.username!!)
Even though we do know the value is not null from the context, the Kotlin compiler has no way to infer this information. So, we have to use the !! operator here.
4. Conclusion
In this quick tutorial, we got familiar with another aspect of nullability in Kotlin: the not-null assertion operator.
As usual, all the samples are available over on GitHub.