What is lateinit Property in Kotlin: Simple Explanation and Example
lateinit property is a variable that you promise to initialize later before using it, avoiding the need to assign it a value at declaration. It can only be used with non-nullable var properties of object types and helps prevent null checks when you are sure the property will be initialized.How It Works
Imagine you have a box that you want to fill later, but you want to tell everyone that the box will definitely be filled before anyone tries to open it. In Kotlin, lateinit works like that promise for a variable. You declare the variable without giving it a value right away, but you guarantee it will be set before use.
This is useful because Kotlin normally requires you to initialize variables when you declare them or mark them as nullable. With lateinit, you avoid making the variable nullable and avoid extra null checks, but you must be careful to initialize it before accessing it, or the program will crash.
Example
lateinit variable and initialize it later before use.class User { lateinit var name: String fun initializeName() { name = "Alice" } fun printName() { if (this::name.isInitialized) { println("User name is: $name") } else { println("Name is not initialized yet.") } } } fun main() { val user = User() user.printName() // Before initialization user.initializeName() user.printName() // After initialization }
When to Use
Use lateinit when you have a non-null property that cannot be initialized at the moment of object creation but will definitely be set before use. This is common in dependency injection, unit testing, or Android development where views or components are initialized later.
For example, in Android apps, UI elements are often initialized after the layout is loaded, so lateinit lets you declare variables for these elements without making them nullable.
Key Points
- Only for
varproperties: You cannot uselateinitwithval. - Non-nullable types only: It cannot be used with nullable types.
- Must be initialized before use: Accessing before initialization throws
UninitializedPropertyAccessException. - Check initialization: Use
::property.isInitializedto check if it is set.
Key Takeaways
lateinit to declare non-null variables that will be initialized later.var properties of non-null types.lateinit property before initialization causes a runtime error.lateinit property is initialized using ::property.isInitialized.