0
0
KotlinDebug / FixBeginner · 4 min read

How to Fix 'lateinit property not initialized' Error in Kotlin

The lateinit property not initialized error happens when you try to use a lateinit variable before assigning it a value. To fix it, ensure you initialize the variable before accessing it, or check if it is initialized using ::variable.isInitialized before use.
🔍

Why This Happens

The error occurs because lateinit variables in Kotlin promise to be initialized before use, but if you access them too early, Kotlin throws an exception. This is like promising to bring a book to a friend but forgetting it at home when they ask for it.

kotlin
class Example {
    lateinit var text: String

    fun printText() {
        println(text) // Accessing before initialization
    }
}

fun main() {
    val example = Example()
    example.printText() // Error here
}
Output
Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property text has not been initialized
🔧

The Fix

To fix this, assign a value to the lateinit variable before using it. Alternatively, check if it is initialized using ::variable.isInitialized to avoid the error.

kotlin
class Example {
    lateinit var text: String

    fun initialize() {
        text = "Hello, Kotlin!"
    }

    fun printText() {
        if (this::text.isInitialized) {
            println(text)
        } else {
            println("text is not initialized yet")
        }
    }
}

fun main() {
    val example = Example()
    example.initialize() // Initialize before use
    example.printText() // Prints: Hello, Kotlin!
}
Output
Hello, Kotlin!
🛡️

Prevention

To avoid this error in the future, always initialize lateinit variables before accessing them. Use ::variable.isInitialized to check initialization safely. Consider using nullable types (String?) if initialization might be delayed or optional, which forces you to handle nulls explicitly.

Also, enable Kotlin compiler warnings and use static analysis tools to catch uninitialized lateinit variables early.

⚠️

Related Errors

Similar errors include:

  • NullPointerException: Happens when accessing a null variable without checking.
  • UninitializedPropertyAccessException: The exact error for uninitialized lateinit variables.
  • IllegalStateException: Sometimes thrown if a variable is used in an invalid state.

Quick fixes involve proper initialization and null checks.

Key Takeaways

Always initialize lateinit variables before accessing them to avoid runtime errors.
Use ::variable.isInitialized to check if a lateinit variable is ready to use.
Consider nullable types if initialization timing is uncertain to force safe handling.
Enable compiler warnings and static analysis to catch uninitialized variables early.