How to Handle Null in Kotlin: Safe Calls and Null Checks
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.
fun main() {
val name: String = null
println(name.length)
}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.
fun main() {
val name: String? = null
println(name?.length ?: "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.
fun main() {
val text: String? = null
println(text!!.length) // Throws NullPointerException
}Key Takeaways
? when they can hold null.?. to access nullable variables safely.?: to provide default values for nulls.!! unless you are sure the value is not null.