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
!!operator β force-unwrapping a null value- Java interop β Java methods can return null even when Kotlin expects non-null
lateinitnot initialized β accessing alateinit varbefore 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 hasUnsafeCallOnNullableType). - 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