Quick Answer

Non-null properties initialized after construction

Understanding the Issue

lateinit allows declaring non-null properties that will be initialized later, before being accessed. Useful for dependency injection or test setup.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Nullable property
var service: Service? = null

fun useService() {
    service?.doWork() // Need safe call
}

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution: lateinit
lateinit var service: Service

fun useService() {
    if (::service.isInitialized) {
        service.doWork() // Direct access
    }
}

Key Takeaways

Use lateinit for properties initialized outside constructor, but before use.