lateinit vs lazy Property in Kotlin
We wish to declare a variable but don’t want to initialize it during creation because we are certain that before going for the execution, it’ll definitely be initialized at some point in the program.
Here, we have two choices one is to declare a variable as nullable which often causes us trouble because there are functions that demand additional handling of nullable values. So here comes our very important and beautiful feature of Kotlin – the lateinit. The Lateinit in Kotlin is a trustworthy keyword that takes the responsibility on its head and says to the compiler:
let them declare it for now, I assure you they will initialize it before accessing or using it…
Just one more thing I wanna add is that lateinit has trusted you that you’ll initialize the variable so keep your word and if at any point you’re uncertain about initialization, just put a check using isInitialized. That’s all about lateinit. It was this simple and useful feature. Now let’s look at our second problem statement and see how lazy gets useful.
At times we have some classes whose object Initialization is very heavy and causes our whole program to be delayed.
Don’t go on the name it might be lazy by name but it proves its worth when used. So when object creation is stated to be initialized by using lazy, it doesn’t create the object until the object is called. This was one very important advantage but the second advantage is also interesting. Once the object is initialized we’ll be using the same object again when called, isn’t it interesting, I mean it removes all the overhead of repetitive object creation.
In this above example, we can see that the object of the HeavyClass is created only when it is accessed and also the same object is there all over the main() function.
Please Login to comment...