In Kotlin, properties must be assigned a value upon declaration or during initialization before they can be accessed in any way. However, there are some scenarios where you may not be able to initialize a property when it is declared, but you still want to be able to use it as a normal property later on. This is where the ‘lateinit‘ keyword comes in.
The ‘lateinit‘ keyword allows you to declare a non-null property without initializing it right away. Instead, you can initialize it later in the code before it is used for the first time. Once it is initialized, it is accessed like any other property.
Here’s an example code snippet to demonstrate the use of ‘lateinit‘:
class MyClass {
lateinit var myProperty: String
fun initializeProperty() {
myProperty = "Initialized"
}
fun printMyProperty() {
if (::myProperty.isInitialized) {
println(myProperty)
} else {
println("Property not initialized yet")
}
}
}
fun main() {
val myObj = MyClass()
myObj.printMyProperty() // Output: Property not initialized yet
myObj.initializeProperty()
myObj.printMyProperty() // Output: Initialized
}
In this code, the ‘myProperty‘ property is declared as ‘lateinit‘. The ‘initializeProperty‘ function initializes the property with a string value. The ‘printMyProperty‘ function checks if the property has been initialized using the ‘isInitialized‘ method of the property reference operator ‘::‘. If it has been initialized, the value of the property is printed, otherwise a message indicating that the property has not been initialized yet is printed.
Note that using ‘lateinit‘ on nullable or primitive types is not allowed, as these types cannot be initialized to a default value. Also, accessing an uninitialized ‘lateinit‘ property will result in a ‘UninitializedPropertyAccessException‘. Therefore, it is important to ensure that ‘lateinit‘ properties are properly initialized before accessing them.