In Kotlin, a language widely used for Android development and modern programming due to its expressive syntax and null safety features, the concept of late initialization can be common. This is particularly useful when you have properties in a class that cannot be initialized in the constructor. In this article, we'll look at how to declare and initialize lateinit and lazy variables in Kotlin.
Table of Contents
Using lateinit
The lateinit modifier allows you to tell Kotlin that a certain variable will be initialized later, after its declaration. This modifier is only applicable to var properties and not val. It is often used with non-null properties whose value will be assigned at some point in the lifecycle, especially in frameworks like Android for view binding or dependency injection.
class SampleClass {
lateinit var someString: String
fun initializeString() {
someString = "Kotlin is awesome!"
}
}
With lateinit, you need to be cautious: accessing a lateinit variable before it is initialized will result in an UninitializedPropertyAccessException.
Using lazy
The lazy keyword in Kotlin is another way to delay the initialization of a variable, using val properties. It delegates the variable's initialization until it is accessed for the first time. Once it's accessed, the result is stored and returned subsequently.
class SampleClass {
val someNumber: Int by lazy { computeExpensiveValue() }
private fun computeExpensiveValue(): Int {
println("Computing...")
return 42
}
}
fun main() {
val sample = SampleClass()
println("First access: ")
println(sample.someNumber) // Computation occurs here
println("Second access: ")
println(sample.someNumber) // Uses the cached value
}
In this example, the output would be:
Computing...
First access:
42
Second access:
42
The lazy initialization is particularly useful when your property initialization is time-consuming or resource-intensive. It's a thread-safe implementation by default, making it suitable for multiple-threaded situations.
Comparing lateinit and lazy
lateinitrequires that you initialize before use and is mutable (var), whilelazyis immutable once initialized (val).lateinitis typically used for non-primitive properties, whereaslazycan be used for any property type.- Choose
lateinitif you need to use dependency injections, unit tests or frameworks that require non-null properties.
By using lateinit or lazy, Kotlin developers can manage their application's memory usage and performance more effectively, especially when working with objects that require delayed initialization.