Not Null Assertion in Kotlin: What It Is and How to Use It
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.
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
}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
KotlinNullPointerExceptionif the value is null. - Use it only when you are sure the value is not null.
- Prefer safer null handling operators to avoid crashes.