DEV Community

vmodal_ai
vmodal_ai

Posted on

Kotlin Null Safety Best Practices: Avoid NullPointerException Like a Pro

One of Kotlin's biggest advantages over Java is its built-in null safety. By making nullability part of the type system, Kotlin helps you catch many errors at compile time instead of at runtime.

In this tutorial, we'll look at the essential null safety features every Kotlin developer should know.

Nullable vs Non-Nullable Types

By default, variables cannot hold null.

val name: String = "Alice"
Enter fullscreen mode Exit fullscreen mode

Trying to assign null results in a compilation error.

If a variable can be null, add a ? to its type.

var name: String? = null
Enter fullscreen mode Exit fullscreen mode

Safe Call Operator (?.)

Use the safe call operator to access properties or methods only when the object isn't null.

val length = name?.length
Enter fullscreen mode Exit fullscreen mode

If name is null, length will also be null instead of throwing an exception.

Elvis Operator (?:)

Provide a default value when an object is null.

val username = name ?: "Guest"
Enter fullscreen mode Exit fullscreen mode

If name is null, "Guest" is returned.

Safe Calls with let

Execute code only when a value is not null.

name?.let {
    println("Hello, $it")
}
Enter fullscreen mode Exit fullscreen mode

The block runs only if name contains a value.

Avoid the Not-Null Assertion (!!)

The !! operator forces Kotlin to treat a nullable value as non-null.

val length = name!!.length
Enter fullscreen mode Exit fullscreen mode

If name is null, your app crashes with a NullPointerException.

Use it only when you're absolutely sure the value cannot be null.

Smart Casts

After checking for null, Kotlin automatically treats the variable as non-null.

if (name != null) {
    println(name.length)
}
Enter fullscreen mode Exit fullscreen mode

There's no need for additional casting.

Best Practices

  • Prefer non-nullable types whenever possible.
  • Use ?. instead of multiple null checks.
  • Use the Elvis operator (?:) to provide default values.
  • Use let to execute code only when a value exists.
  • Avoid !! unless there's no safer alternative.

Conclusion

Kotlin's null safety features make your code safer and easier to read. By using nullable types, safe calls, the Elvis operator, and smart casts, you can eliminate many common runtime crashes caused by NullPointerException.

Learning these patterns early will help you write cleaner, more reliable Kotlin code.

Top comments (0)