In Kotlin, !! is the not-null assertion operator. It forcefully converts a nullable value like String? into a non-null value like String.
val name: String? = getName()
val length = name!!.length
This tells Kotlin:
“Trust me,
nameis not null.”
If name is actually null at runtime, Kotlin throws a NullPointerException.
val name: String? = null
println(name!!.length) // Throws NullPointerException
Why you should avoid !!
You should avoid !! because it bypasses Kotlin’s null-safety system. Kotlin’s nullable types exist specifically to help prevent null-related crashes, and !! effectively says: “ignore that safety check.”
Problems with !!:
- It can cause runtime crashes.
- It hides the fact that a value may be missing.
- It often makes code less clear and less robust.
- It usually means null handling should be improved.
Prefer safer alternatives
Use a safe call
val length = name?.length
If name is null, length becomes null.
Use Elvis operator for a default value
val length = name?.length ?: 0
If name is null, length becomes 0.
Use an explicit null check
if (name != null) {
println(name.length)
} else {
println("Name is missing")
}
Inside the if, Kotlin smart-casts name to a non-null String.
Use let
name?.let {
println(it.length)
}
This only runs the block when name is not null.
Fail deliberately with a clearer message
If null truly represents a programmer error, prefer requireNotNull, checkNotNull, or an explicit error message:
val length = requireNotNull(name) { "Name must not be null" }.length
This still fails fast, but the error is much clearer than a generic NullPointerException.
When is !! acceptable?
Use !! only when you are absolutely certain the value cannot be null, and if it is null, that indicates a serious programming error.
Even then, this is usually better:
val user = requireNotNull(findUser(id)) {
"Expected user with id=$id to exist"
}
Rule of thumb
If you are tempted to write this:
value!!
First ask whether one of these would be better:
value?.someCall()
value ?: defaultValue
if (value != null) { /* use value */ }
requireNotNull(value) { "Helpful error message" }
In most Kotlin code, !! should be rare.
