Quick Answer

Accessing uninitialized lateinit property

Understanding the Issue

Kotlin throws IllegalStateException when accessing a lateinit property that wasn't initialized. This enforces null safety even for properties that can't be initialized in constructors.

The Problem

This code demonstrates the issue:

Kotlin Error
// Problem: Uninitialized access
lateinit var service: Service
fun execute() {
    service.connect() // Crashes if not initialized
}

The Solution

Here's the corrected code:

Kotlin Fixed
// Solution 1: Defensive check
fun execute() {
    if (::service.isInitialized) {
        service.connect()
    }
}

// Solution 2: Initialize properly
fun init(s: Service) {
    service = s
    execute()
}

// Solution 3: Consider nullable type
var service: Service? = null
fun execute() {
    service?.connect() // Safe call
}

Key Takeaways

Always ensure lateinit properties are initialized before use.