Avoiding NullPointerExceptions
Patterns for safe code.
The Goal: No NPEs
A NullPointerException, or NPE, happens when code uses something that is actually null. Kotlin is designed to make these rare.
This lesson brings together the tools you have learned and warns about the few ways an NPE can still sneak in.
The !! Operator
The not-null assertion !! tells the compiler to trust you that a value is not null. If you are wrong, it throws an NPE.
It removes safety, so use it rarely and only when you are certain.
fun main() {
val name: String? = "Ada"
println(name!!.length) // works, name is not null
}All lessons in this course
- Nullable vs Non-Null Types
- Safe Calls and Elvis
- let, also, and Scope Functions
- Avoiding NullPointerExceptions