Junior — Middle
What are the differences between convenience and designated initializers in Swift?
sobes.tech AI
Answer from AI
In Kotlin, lateinit modifier is used for deferred initialization of variables declared with var that cannot be initialized immediately but are guaranteed to be initialized before their first use.
This is convenient when the initialization of a variable depends on external factors, such as dependency injection or in Android when working with components initialized in the lifecycle methods.
Features of lateinit:
- Works only with mutable variables (
var), not withval. - Only applicable to non-primitive types (e.g.,
Int,Booleancannot be used). - If accessed before initialization, it throws
UninitializedPropertyAccessException.
Example:
class Example {
lateinit var data: String
fun initialize() {
data = "Hello"
}
fun printData() {
println(data) // Error if called before initialize()
}
}
Thus, lateinit allows avoiding nullable types and null checks when you are sure the variable will be initialized later.