Late and lazy inits
Amit Nadiger
Polyglot(Rust??, C++ 11,14,17,20, C, Kotlin, Java) Android TV, Cas, Blockchain, Polkadot, UTXO, Substrate, Wasm, Proxy-wasm,AndroidTV, Dvb, STB, Linux, Engineering management.
In Kotlin, late initialization and lazy initialization are two different techniques that are used to improve the efficiency of code execution and memory usage. The lateinit keyword is used to declare a non-null variable that can be initialized later, while lazy is a function that is used to create a lazily initialized variable.
With lateinit, we can declare a variable without initializing it and then later set its value. This is useful when we want to avoid the overhead of initializing a variable at the time of declaration, but still want to ensure that the variable is not null. On the other hand, with lazy, we can create a variable that will only be initialized when it is accessed for the first time. This is useful when we want to defer the initialization of a variable until it is actually needed, which can help to improve the performance of our code.
lateinit (applicable only to var):
In Kotlin, we can declare variables without initializing them, but we must assign a value to them before using them. However, sometimes we may not have the initial value for a variable at the time of declaration, but we still want to declare it. To handle such scenarios, Kotlin provides a lateinit keyword. It allows us to delay the initialization of a variable until it is needed. lateinit is a modifier that is used with non-null properties. It is used to indicate to the compiler that the property will be initialized at a later point in the code and should not be initialized during object creation.
What is Late Initialization?
Late initialization is a mechanism that allows properties to be declared without an initial value and initialized later before their first use. It is particularly useful when the initialization of a property depends on some external factors or when the initialization logic is complex and cannot be executed at the time of declaration.
The lateinit keyword is useful in situations where you cannot initialize a property immediately after object creation, but still need to declare it as non-null. For example, when dealing with dependency injection frameworks, the object creation and property initialization can be separated in time.
Using the lateinit modifier allows you to declare the property as non-null and initialize it at a later point, without the need to declare it as nullable and potentially dealing with null checks throughout the code.
However, it is important to note that lateinit can only be used with mutable properties (i.e., var), and only with properties that are not initialized in the constructor. Additionally, if you try to access a lateinit property before it has been initialized, a NullPointerException will be thrown at runtime. Therefore, it is important to ensure that the property is initialized before it is accessed, or to use a null-check before accessing it.
class Example {
? ? private lateinit var name: String
? ? fun initializeName(name: String) {
? ? ? ? this.name = name
? ? ? ? println("Name is initialized now.")
? ? }
? ? fun printName() {
? ? ? ? if (::name.isInitialized) {
? ? ? ? ? ? println("Name is: $name")
? ? ? ? } else {
? ? ? ? ? ? println("Name is not initialized yet.")
? ? ? ? }
? ? }
}
fun main() {
? ? val example = Example()
? ? example.printName() // Output: Name is not initialized yet.
? ? example.initializeName("Amit")
? ? example.printName() // Output: Name is: John
}
/*
Op =>
Name is not initialized yet.
Name is initialized now.
Name is: Amit
*/
Constraints of Late Initialization:
Advantages of using lateinit in Kotlin:
Disadvantages of using lateinit in Kotlin:
Suitable scenario to use lateinit:
The lateinit keyword can be used in scenarios where a non-null property cannot be initialized during object creation, but its initialization can be deferred until a later point in the code. Some suitable scenarios for using lateinit include:
It is important to note that lateinit should be used judiciously, as it can lead to runtime exceptions if the property is not initialized before it is accessed. It should only be used when it is absolutely necessary and when the developer is confident that the property will be initialized before it is accessed.
Lazy initialization(Applicable only to val):
Lazy initialization is a technique in programming where a resource or object is initialized only when it is first accessed, rather than at the time of creation. In Kotlin, we can use the "lazy" keyword to declare a property with lazy initialization.
领英推荐
What is Lazy Initialization?
Lazy initialization is a design pattern that defers the creation or initialization of an object or property until it is accessed for the first time. Instead of eagerly initializing the object or property, lazy initialization waits until it is actually needed. This can be particularly useful when dealing with computationally expensive operations, heavy I/O operations, or expensive resource allocations.
The "lazy" keyword is used to define a lazy-initialized property in Kotlin. It takes a lambda expression that computes the value of the property when it is first accessed. The property is initialized only once, on the first access, and subsequent accesses return the previously computed value.
Example:
class MyClass {
? ? val myLazyName: String by lazy {
? ? ? ? println("Initializing...")
? ? ? ? "RamaChandra!"
? ? }
}
fun main() {
? ? val obj = MyClass()
? ? println("Before accessing lazy property")
? ? println(obj.myLazyName)
? ? println("After accessing lazy property")
? ? println(obj.myLazyName)
}
/*
Before accessing lazy property
Initializing...
RamaChandra!
After accessing lazy property
RamaChandra!
*/
In the above example, we have a class MyClass that has a property myLazyName which is declared using the lazy keyword. The myLazyName property is initialized with a lambda expression that returns a string "Hello, World!" and also prints "Initializing..." to the console.
In the main() function, we create an instance of MyClass and print a message "Before accessing lazy property". Then we access the myLazyName property by printing it to the console. Since this is the first time myLazyName is accessed, its initialization code is executed and "Initializing..." is printed to the console. Finally, we print another message "After accessing lazy property" and again access myLazyName. Since myLazyName has already been initialized, its initialization code is not executed again.
Constraints of Lazy Initialization:
Advantages of lazy initialization:
Disadvantages of lazy initialization:
Suitable scenarios to use lazy initialization:
Applications of lateinit and lazy init in android :
In Android development, both lateinit and lazy initialization techniques are commonly used to improve the performance of an application.
lateinit can be used to delay the initialization of a property until its first usage, which can save resources and improve performance. In Android, lateinit is often used to delay the initialization of views, which can be a time-consuming operation. By using lateinit, the view is only initialized when it is first accessed, rather than when the activity is created, which can improve the startup time of the application.
On the other hand, lazy initialization is used to delay the creation of an object until its first usage. This technique can also save resources and improve performance. In Android, lazy initialization is often used for expensive operations, such as database queries or network requests. By using lazy, the operation is only performed when the object is first accessed, rather than when the activity is created, which can improve the responsiveness of the application.
For example, consider a scenario where an application needs to fetch some data from a remote server when a user clicks a button. By using lazy, the network request can be delayed until the button is clicked, rather than performing the request when the activity is created. This can improve the performance of the application and make it more responsive to user input.
In summary, both lateinit and lazy initialization techniques can be used in Android development to improve the performance and responsiveness of an application. lateinit is often used to delay the initialization of views, while lazy is used to delay the creation of expensive objects or perform expensive operations.
Thanks for reading till end , please comment if you have anything .