When should you use Lateinit over Lazy initialization in Kotlin?
The Lateinit and Lazy initializations are two initialization properties in the Kotlin language. It is necessary to know when to use Lateinit and when to use theLazy initialization.
When To Use Lateinit
Use Lateinit:
- to initialize a variable late.
- when you are sure about initializing a variable before using it.
- with the
varkeyword. - if variables change at a later stage, i.e., if the variable is mutable.
Lateinit variables can be declared inside the class.
Lateinitdoes not allocate memory before initializing.
What to avoid while using Lateinit
- While using
Lateinit, the variable can’t be of the null type. Lateinitcannot be used for primitive datatypes, i.e., Long and int.- If you try accessing
Lateinitvariables without initializing, it will throw an exception stating that it is not initialized or properly being accessed.
private lateinit var educativeshot : educativeshot
It can later on be initialized in the educativeshot class
educativeshot = educative()
When to use Lazy initialization
- In the
Lazyinitialization, your variable will not be initialized unless you call/use it. - The
Lazyinitialization initializes the variable once; that same value is then used throughout the code. - It is used for read-only properties as the same valued variable is used throughout.
- This initialization is used in the case of the
valproperty. -It is preferred when the variable is to be shared by all and only initialized once. - It can be used when an object is dependent on a variable internal to the class.
What to avoid while using the Lazy initialization
- The code spreads throughout the class at an undecided time, which can lead to confusion.
- The
Lazyobject returns the previously initialized value when accessed later. - The
LazyInitialization causes memory leakage when used on a retained fragment as it holds a reference to the old view.
val educative: String by lazy {val educativeshot = "this value"}
class educative{private val edobject: educativeshot by lazy {educativeshot()}}
Lateinit vs. Lazy initialization
- In case a property does not have a custom setter and getter,
Lateinitis used. - In a mult-threaded environment,
Lateinitinitialization is dependent on the user. - The
Lazyinitialization is thread-safe. Lateinitcan only be used withvar.Lazyinitialization is used with thevalproperty.