Junior
Explain how the 'lateinit' property works in Kotlin.
sobes.tech AI
Answer from AI
lateinit is used for declaring non-nullable properties that will be initialized later, before their first use.
- It applies only to mutable properties (
var). - It cannot be used with primitive data types (like
Int,Boolean,Float) because they cannot benull. - The compiler does not require immediate initialization of the property upon declaration.
- If the property is used before initialization, an
UninitializedPropertyAccessExceptionwill be thrown.
Example:
class MyClass {
lateinit var myProperty: String // Property will be initialized later
fun initializeProperty(value: String) {
myProperty = value
}
fun useProperty() {
println(myProperty) // Safe after initialization
}
}
fun main() {
val obj = MyClass()
// obj.useProperty() // Will throw UninitializedPropertyAccessException here
obj.initializeProperty("Hello")
obj.useProperty() // Will print "Hello"
// Check if initialized
if (obj::myProperty.isInitialized) {
println("Property is initialized")
}
}
You can check if a lateinit property has been initialized using reflection: ::propertyName.isInitialized.
The use of lateinit is common in frameworks where properties are injected (dependency injection) after object creation (for example, in Android with UI elements or dependency injection).