Sobes.tech
Junior — Middle

What is the purpose of the lateinit modifier in Kotlin?

sobes.tech AI

Answer from AI

The lateinit modifier in Kotlin is used for deferred initialization of variables declared with a non-null type (usually var variables). It allows declaring a variable without an initial value but guarantees that it will be initialized before its first use. This is convenient, for example, for properties that are initialized later, such as in the onCreate method in Android.

Example:

lateinit var database: Database

fun setup() {
    database = Database()
}

fun query() {
    database.query("SELECT * FROM users")
}

Trying to access database before initialization will throw an UninitializedPropertyAccessException. lateinit can only be used with var and not with primitive types.