Kotlin library provides two different access modifiers for property declaration.
In this article, we will highlight the difference between these two access modifiers and how we can use them in our application.
Lateinit
In order to create a "lateInit" variable, we just need to add the keyword "lateInit" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use "lateInit" in Kotlin.
Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".
"lateInit" is allowed only with non-NULLable data types.
"lateInit" does not work with primitive data types.
"lateInit" can be used when the variable property does not have any getter and setter methods.
Example
We will be declaring a variable as lateInit and we will see how we can access the same throughout the program.
class Tutorial { lateinit var name : String fun checkLateInit(){ // checking whether the value is assigned or not if(this::name.isInitialized) println("Your value is not assigned"); else{ // initializing name name = "www.tutorialspoint.com/" println(this.name) // this will return true } } } fun main() { var obj=Tutorial(); obj.checkLateInit(); }
Output
Once you execute the code, it will generate the following output −
www.tutorialspoint.com/
Lazy Initialization
For efficient memory management, Kotlin has introduced a new feature called as Lazy initialization. When the lazy keyword is used, the object will be created only when it is called, otherwise there will be no object creation. lazy() is a function that takes a lambda and returns an instance of lazy which can serve as a delegate of lazy properties upon which it has been applied. It has been designed to prevent unnecessary initialization of objects.
Lazy can be used only with non-NULLable variables.
Variable can only be val. "var" is not allowed .
Object will be initialized only once. Thereafter, you receive the value from the cache memory.
The object will not be initialized until it has been used in the application.
Example
In this example, we will declare a lazy variable "myName" and we could see that the call to this parts of the code will happen only once and when the value is initialized, it will remember the value throughout the application. Once the value is assigned using lazy initialization, it cannot be reassigned .
class Demo { val myName: String by lazy { println("Welcome to Lazy declaration"); "www.tutorialspoint.com" } } fun main() { var obj=Demo(); println(obj.myName); println("Second time call to the same object--"+obj.myName); }
Output
Once you execute the code, it will generate the following output −
Welcome to Lazy declaration www.tutorialspoint.com Second time call to the same object--www.tutorialspoint.com