0
0
KotlinConceptBeginner · 3 min read

Not Null Assertion in Kotlin: What It Is and How to Use It

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 actually null, it throws a KotlinNullPointerException at runtime.
⚙️

How It Works

The not null assertion operator !! in Kotlin is like telling the program, "I am sure this value is not null." It takes a variable that might hold a null and forces it to be treated as non-null. If the value is indeed not null, the program continues smoothly.

Think of it like crossing a bridge that sometimes might be broken. Using !! is like saying, "I know the bridge is safe," but if it turns out broken (the value is null), you fall and get an error (KotlinNullPointerException).

This operator is useful when you are certain a value cannot be null at a specific point, but Kotlin's type system still treats it as nullable.

💻

Example

This example shows how !! works by forcing a nullable string to be non-null and printing its length. If the string is null, the program throws an error.

kotlin
fun main() {
    val nullableString: String? = "Hello"
    println(nullableString!!.length)  // Prints length because value is not null

    val nullString: String? = null
    println(nullString!!.length)  // Throws KotlinNullPointerException
}
Output
5 Exception in thread "main" kotlin.KotlinNullPointerException at MainKt.main(main.kt:7)
🎯

When to Use

Use the not null assertion operator only when you are absolutely sure a nullable value is not null at that point in your code. It is a way to override Kotlin's safety checks.

Common real-world cases include:

  • Interacting with Java code where nullability is not clear.
  • After checking a value for null explicitly, then using !! to tell Kotlin it is safe.
  • Quick prototyping or small scripts where you want to avoid extra null checks.

However, overusing !! can lead to crashes, so prefer safer options like ?. (safe call) or ?: (elvis operator) when possible.

Key Points

  • !! converts nullable to non-null but throws if null.
  • It causes a KotlinNullPointerException if the value is null.
  • Use it only when you are sure the value is not null.
  • Prefer safer null handling operators to avoid crashes.

Key Takeaways

The not null assertion operator (!!) forces a nullable value to be non-null but throws an exception if null.
Use !! only when you are certain the value cannot be null at runtime.
Prefer safe calls (?.) and the elvis operator (?:) for safer null handling.
Overusing !! can cause unexpected crashes due to KotlinNullPointerException.
It is useful when working with Java code or after explicit null checks.