/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
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
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
| Situation | Fix |
|---|---|
| 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 Hilt | Annotate the Activity or Fragment with @AndroidEntryPoint |
| Adapter or callback runs before setup | Initialize the property in the constructor or check isInitialized |
Sources
Related pages
errors · kotlinKotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?Kotlin rejects a plain dot call on a nullable type like String?. Use ?. for a null result, ?: for a default, or check for null first so the value is smart-cast.compare · kotlinKotlin val vs var: read-only vs mutable variablesIn Kotlin, val declares a read-only reference assigned once and var a mutable one. A val object can still change inside. When to use each one, and const val.errors · javajava.lang.NullPointerException: Cannot invoke "String.length()" because "name" is nullJava's helpful NullPointerException names the call that failed and the null variable. Why it can say <local1> instead of a name, and how to fix the null.