Non-Null Assertion
In this page:
Using the !! Operator
Appending !! to a nullable expression asserts to the compiler that the value is definitely not null, allowing direct, non-nullable-style access -- but it throws immediately at runtime if that assumption is wrong.
Example: Using the !! Operator
fun main() {
val name: String? = "Kotlin"
val length = name!!.length
println("Length: $length")
}
Login to try C/C++/Java/PHP code in the editor
The Danger of !! on Actual Nulls
If the asserted value really is null at runtime, !! throws a NullPointerException immediately, which is exactly the kind of crash Kotlin's null safety was designed to prevent.
Example: The Danger of !! on Actual Nulls
fun main() {
val name: String? = "Kotlin"
try {
val other: String? = null
println(other!!.length)
} catch (e: NullPointerException) {
println("Caught NPE: as expected when forcing a null value")
}
println("Safe name length: ${name!!.length}")
}
Login to try C/C++/Java/PHP code in the editor
Preferring Safer Alternatives
In almost every case, ?., ?:, or an explicit if (value != null) check communicates intent more clearly and avoids crashing, making !! unnecessary.
Note: Reach for !! only when you can prove, from the surrounding logic, that the value cannot possibly be null.
Example: Preferring Safer Alternatives
fun main() {
val name: String? = null
// Prefer this over `name!!.length`
val length = name?.length ?: 0
println("Safe length: $length")
}
Login to try C/C++/Java/PHP code in the editor
When !! Can Be Justified
A rare acceptable use is right after a null check performed in a way the compiler cannot smart-cast, such as through a separately stored Boolean flag, where the developer has genuinely already ruled out null.
Example: When !! Can Be Justified
fun main() {
val values = mutableMapOf("count" to 5)
if (values.containsKey("count")) {
println("Count is ${values["count"]!!}")
}
}
Login to try C/C++/Java/PHP code in the editor
- Overusing
!!as a quick way to silence compiler warnings, reintroducing the very null pointer exceptions Kotlin's type system tries to prevent. - Using
!!on a value from user input or a network response, where nullness is genuinely uncertain at runtime. - Forgetting that
!!throws aNullPointerException(technicallyKotlinNullPointerException) immediately if the value actually isnull.
!!forcibly treats a nullable value as non-null, throwing an exception immediately if it is actuallynull.!!should be a last resort, used only when you are certain a value cannot benullat that point.- Overusing
!!defeats the purpose of Kotlin's null-safety system and can reintroduce null pointer crashes. - Safer alternatives like
?.,?:, and explicitifchecks are almost always preferable to!!.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: