0
0
KotlinConceptBeginner · 3 min read

What is !! Operator in Kotlin: Explanation and Usage

In Kotlin, the !! operator is called the not-null assertion operator. It converts any value to a non-null type and throws a KotlinNullPointerException if the value is null.
⚙️

How It Works

The !! operator in Kotlin is like a safety check override. Imagine you have a box that might be empty (null) or have something inside (a value). Normally, Kotlin asks you to check if the box is empty before taking something out. But if you use !!, you are telling Kotlin, "I am sure this box is not empty," and you want to take the value directly.

If the box turns out to be empty anyway, Kotlin will throw a KotlinNullPointerException, which is like an alarm that says you made a wrong assumption. This operator forces Kotlin to treat a nullable value as non-nullable, skipping the usual safety checks.

💻

Example

This example shows how !! works by forcing a nullable string to be non-null. If the string is null, the program crashes with an exception.

kotlin
fun main() {
    val nullableString: String? = null
    // Using !! to assert non-null
    val nonNullString: String = nullableString!!
    println(nonNullString)
}
Output
Exception in thread "main" kotlin.KotlinNullPointerException
🎯

When to Use

You should use the !! operator only when you are absolutely sure a value is not null, but Kotlin's type system cannot prove it. For example, when working with legacy code or APIs that return nullable types but you know the value is safe.

However, it is better to avoid !! because it can cause crashes. Instead, use safe calls (?.), the Elvis operator (?:), or explicit null checks to handle nulls gracefully.

Key Points

  • !! forces a nullable value to be non-null.
  • Throws KotlinNullPointerException if the value is null.
  • Use sparingly and only when sure the value is not null.
  • Prefer safer null handling methods to avoid crashes.

Key Takeaways

The !! operator asserts a value is not null and throws an exception if it is.
Use !! only when you are certain the value cannot be null at runtime.
Avoid !! when possible; prefer safe calls or null checks for safer code.
Using !! incorrectly can cause your program to crash with a NullPointerException.