Lateinit & Lazy in kotlin
Hey guys, In this Tech-blog we will try to learn about Lateinit & Lazy. We try to see in different scenarios what the output will be.
Lateinit in kotlin
As the name said (late -> later) + (init -> initialization). like it is only use with var property and It can we initalize latter. Hey we declear variable with promise that we will initalize it be accessing this variable.
✅Do’s :)
Above code is the idea way to declear lateinit variable. Let’s decusses about some don’t condition.
❌Dont’s
What happen when we access initialization variable before initalzation?
Ans. NO :(
You will get UninitializedPropertyAccessException. Almost same as nullPointerException. For checking that property is initialized or not you can check by “isInitialized”.
✅Do’s
Can we do lateinit initialization multiple time?
Ans. YES :)
❌Dont’s
Can we create lateinit of val type?
Ans. NO :(
❌Dont’s
Can lateinit modefire is allowed for Primitive data type?
Ans. No :(
❌Dont’s
Can lateinit modefire be nullable type?
Ans. No :(
Lazy in kotlin
As the name said lazy procrastinate work, do work when it is very impotent . Just before deadline. Same lazy property do initialization of lazy variable(Object) when it access(Used) first time. For Example If one class dep. on two class then if you create object of that class normally then Creation of that class take more time as compare to lazy object creation way.
✅Do’s :)
❌Dont’s
Lazy property can we of var type?
Ans. No :(
✅ Facts
“A lateinit property can’t have a custom getter whereas a lazy property has a block that gets executed whenever the first time that property is called.”
“Since the lazy block returns an object which implements the Lazy interface, we can check if the variable is initialised or not in the case of the lazy property also but for that, we need to split the lazy call.”
✅Do’s :)
Lazy Property can be of primitive date types?
Ans. yes :)
✅Do’s :)
Thready safety?
Ans. We can’t define the thready safety in case of lateinit property but in case of lazy, we can choose between SYNCHRONIZED, PUBLICATION and NONE.
✅Do’s :)
Lazy can be nullable?
Ans. Yes :)
Summary
“Keep Exploring, Keep Learing, Keep sharing”
Happy Coding
Thank you. :)