Skip to content

/errors/kotlin/lateinit-property-has-not-been-initialized

kotlin.UninitializedPropertyAccessException: lateinit property has not been initialized

The commands on this page have not been executed by our verification runner yet.updated
tool
Kotlin
versions
Kotlin 1.2+ (isInitialized), Kotlin 2.x
os
any

kotlin.UninitializedPropertyAccessException: lateinit property NAME has not been initialized is thrown when code reads a lateinit var before anything assigned it. lateinit tells the compiler "this non-null property will be set later", so the compiler cannot check it; the check happens at run time and fails with this exception. Assign the property earlier, check ::name.isInitialized before reading it, or replace it with by lazy { } or a nullable type.

Example

kotlin
class ReportService {
    lateinit var repository: Repository

    fun count(): Int = repository.size()   // read before anyone set it
}

fun main() {
    ReportService().count()
    // Exception in thread "main" kotlin.UninitializedPropertyAccessException:
    //     lateinit property repository has not been initialized
}

Fixes

kotlin
class ReportService(private val repository: Repository) {    // 1. constructor injection: no lateinit
    fun count(): Int = repository.size()
}

class Screen {
    lateinit var title: String
    fun render() {
        if (this::title.isInitialized) println(title)          // 2. check before reading
    }
}

class Config {
    val settings: Map<String, String> by lazy { loadSettings() } // 3. computed on first access
}

Android

SituationFix
lateinit var binding read before onCreate()Set it in onCreate() before any use; do not read it in property initializers
Fragment binding read after onDestroyView()Use a nullable _binding and clear it in onDestroyView()
@Inject lateinit var with HiltAnnotate the Activity or Fragment with @AndroidEntryPoint
Adapter or callback runs before setupInitialize the property in the constructor or check isInitialized

Sources