0
0
KotlinDebug / FixBeginner · 3 min read

How to Handle Null in Kotlin: Safe Calls and Null Checks

In Kotlin, you handle null by declaring variables as nullable using ? and safely accessing them with ?. or providing defaults with the ?: operator. This prevents NullPointerException by forcing you to check for null before use.
🔍

Why This Happens

Kotlin does not allow null values in regular variables by default. If you try to assign or use a null value without marking the variable as nullable, the compiler will give an error. If you force null usage without checks, it causes a NullPointerException at runtime.

kotlin
fun main() {
    val name: String = null
    println(name.length)
}
Output
error: null can not be a value of a non-null type String
🔧

The Fix

To fix this, declare the variable as nullable by adding ? after the type. Use safe calls ?. to access properties or methods only if the value is not null. Use the Elvis operator ?: to provide a default value if null.

kotlin
fun main() {
    val name: String? = null
    println(name?.length ?: "No name provided")
}
Output
No name provided
🛡️

Prevention

Always declare variables as nullable only when they can hold null. Use safe calls ?. and the Elvis operator ?: to handle null safely. Avoid using the not-null assertion !! unless you are sure the value is not null, as it throws exceptions otherwise. Enable Kotlin's null-safety linting in your IDE to catch unsafe null usage early.

⚠️

Related Errors

Common related errors include NullPointerException when using !! on a null value, and compiler errors when assigning null to non-null types. To fix these, use nullable types and safe calls as shown above.

kotlin
fun main() {
    val text: String? = null
    println(text!!.length) // Throws NullPointerException
}
Output
Exception in thread "main" kotlin.KotlinNullPointerException

Key Takeaways

Declare variables as nullable with ? when they can hold null.
Use safe calls ?. to access nullable variables safely.
Use the Elvis operator ?: to provide default values for nulls.
Avoid using !! unless you are sure the value is not null.
Enable null-safety linting to catch null-related issues early.