0
0
KotlinHow-ToBeginner · 3 min read

How to Use Not Null Assertion in Kotlin: Simple Guide

In Kotlin, the not null assertion operator !! converts a nullable type to a non-null type by asserting the value is not null. If the value is null, it throws a NullPointerException. Use !! when you are sure a variable is not null but the compiler cannot guarantee it.
📐

Syntax

The not null assertion operator is written as !! immediately after a nullable variable or expression. It tells Kotlin to treat the value as non-null.

  • variable!!: Asserts variable is not null.
  • If variable is null, a NullPointerException is thrown.
kotlin
val nullableString: String? = "Hello"
val nonNullString: String = nullableString!!
💻

Example

This example shows how to use the not null assertion operator to convert a nullable string to a non-null string. It also shows what happens if the value is null.

kotlin
fun main() {
    val nullableName: String? = "Kotlin"
    val name: String = nullableName!!
    println("Name is: $name")

    val nullName: String? = null
    // The next line will throw NullPointerException
    // val errorName: String = nullName!!
    // println(errorName)
}
Output
Name is: Kotlin
⚠️

Common Pitfalls

Using !! can cause your program to crash with a NullPointerException if the value is actually null. Avoid overusing it and prefer safe calls or null checks.

Wrong way: blindly using !! without checking for null.

Right way: check for null before using !! or use safe calls ?. and the Elvis operator ?:.

kotlin
fun main() {
    val maybeNull: String? = null

    // Wrong: throws NullPointerException
    // val forced: String = maybeNull!!

    // Right: check before asserting
    if (maybeNull != null) {
        val safe: String = maybeNull
        println(safe)
    } else {
        println("Value is null, cannot assert")
    }

    // Or use safe call with default
    val defaultName: String = maybeNull ?: "Default"
    println(defaultName)
}
Output
Value is null, cannot assert Default
📊

Quick Reference

Summary tips for using the not null assertion operator:

  • Use !! only when you are sure the value is not null.
  • It throws NullPointerException if the value is null.
  • Prefer safe calls ?. and null checks to avoid crashes.
  • Use ?: to provide default values when null.

Key Takeaways

The not null assertion operator (!!) converts nullable types to non-null but throws if null.
Use !! only when you are certain the value is not null to avoid runtime crashes.
Prefer safe calls (?.) and the Elvis operator (?:) for safer null handling.
NullPointerException occurs if !! is used on a null value.
Check for null explicitly before using !! to write safer Kotlin code.