Quick Answer
Deferred initialization of non-null properties
Understanding the Issue
lateinit allows non-null properties to be initialized after construction but before use. The property must be mutable (var) and cannot have a custom getter/setter.
The Problem
This code demonstrates the issue:
Kotlin
Error
// Problem: Accessing uninitialized lateinit
lateinit var service: Service
fun useService() {
service.connect() // Crash if not initialized
}
The Solution
Here's the corrected code:
Kotlin
Fixed
// Solution 1: Initialize before use
fun initService(s: Service) {
service = s
}
// Solution 2: Check initialization
fun useService() {
if (::service.isInitialized) {
service.connect()
}
}
// Solution 3: Consider dependency injection
Key Takeaways
Ensure lateinit properties are initialized before access.