πŸ”§ Error Fixes
Β· 1 min read

Kotlin: NullPointerException β€” How to Fix It


Kotlin is supposed to prevent NPEs, but you can still get them from Java interop, the !! operator, or lateinit variables.

Why this happens

Kotlin’s null safety system only works within pure Kotlin code. When calling Java libraries, return types become β€œplatform types” with unknown nullability, so Kotlin can’t enforce null checks. Additionally, the !! operator explicitly tells the compiler to skip null safety, and lateinit variables bypass initialization checks at compile time.

What causes this error

  1. !! operator β€” force-unwrapping a null value
  2. Java interop β€” Java methods can return null even when Kotlin expects non-null
  3. lateinit not initialized β€” accessing a lateinit var before assignment

Fix 1: Replace !! with safe calls

// ❌ Crashes if user is null
val name = user!!.name

// βœ… Safe call β€” returns null if user is null
val name = user?.name

// βœ… Safe call with default
val name = user?.name ?: "Unknown"

Fix 2: Handle Java nullability

// Java method might return null
val result: String? = javaObject.getName()  // Mark as nullable
val safe = result ?: "default"

Fix 3: Check lateinit before access

lateinit var adapter: MyAdapter

// βœ… Check before using
if (::adapter.isInitialized) {
    adapter.update()
}

Alternative solutions

Use let for scoped null checks β€” cleaner than if-else for chained operations:

user?.let { u ->
    println(u.name)
    sendEmail(u.email)
}

Add @Nullable/@NonNull annotations to Java code so Kotlin can enforce null safety at the boundary.

Prevention

  • Ban !! in your codebase via a lint rule (detekt has UnsafeCallOnNullableType).
  • Always declare types from Java interop as nullable (String?) unless you’re certain they can’t be null.

Related: Java: NullPointerException fix Β· C#: NullReferenceException fix