Quick Answer

Null safety violations in Kotlin

Understanding the Issue

While Kotlin's type system prevents most NPEs, they can still occur with: lateinit property access, Java interop, !! operator, or platform types from Java.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Possible NPE sources
lateinit var config: Configuration
fun init() {
    config.load() // NPE if not initialized

    val javaValue: String = JavaClass.nullableValue()
    println(javaValue.length) // Potential NPE
}

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution 1: Check lateinit
if (::config.isInitialized) {
    config.load()
}

// Solution 2: Handle Java nulls
val javaValue: String? = JavaClass.nullableValue()
println(javaValue?.length ?: 0)

// Solution 3: Avoid !! operator
val length = nullableString!!.length // Risky

Key Takeaways

Be cautious with lateinit, Java interop, and !! to prevent NPEs.