Non-Null Assertion
In this page:
val value = nullable!! // throws NullPointerException if null
val safer = nullable ?: defaultValue
val safer = nullable?.member
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
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `name` (a `String?`), set to `"Kotlin"`
val name: String? = "Kotlin"
// Declare a read-only variable `length`, set to `name!!.length`
val length = name!!.length
// Print "Length: $length" to the console, with a trailing newline
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
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `name` (a `String?`), set to `"Kotlin"`
val name: String? = "Kotlin"
try {
// Declare a read-only variable `other` (a `String?`), set to `null`
val other: String? = null
// Print `other!!.length` to the console, with a trailing newline
println(other!!.length)
} catch (e: NullPointerException) {
// Print "Caught NPE: as expected when forcing a null value" to the console, with a trailing newline
println("Caught NPE: as expected when forcing a null value")
}
// Print "Safe name length: ${name!!.length}" to the console, with a trailing newline
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.
!! 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
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `values`, set to `mutableMapOf("count" to 5)`
val values = mutableMapOf("count" to 5)
// Check whether `values.containsKey("count")`
if (values.containsKey("count")) {
// Print "Count is ${values["count"]!!}" to the console, with a trailing newline
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: