Kotlin lateinit vs lazy
2 min readSep 2, 2020
If we do not want to initialise a variable inside constructor or at start of class then we have two option to initialise details are given below, i’ll try to keep this short and simple.
- lateinit (mutable)
- lazy (immutable)
How to initialise lateinit and lazy
lateinit (can be used only with var)
lateinit var lateInitString: String
fun methodToExecute() {
lateInitString = "can be initialised from anywhere is lateinit"
lateInitString = "variable can be reassigned any number of times"
}
lazy (can be used only with val)
val lazyString: String by lazy{
"must to initialise as lambda"
}
fun methodToExecute() {
//lazyString = "this will give compilation error because lazy variable cannot be reassigned "
}
So, the conclusion is
- lateinit var can be initialised from anywhere, but lazy cannot.
- lazy instance can be stored any used in multiple areas.
- lateinit can be used only with val(immutable) and lazy can only be used with var(mutable).
- lazy is threadsafe
- lateinit doesn’t work with primitive
- lateinit can be initialised multiple time but lazy is allowed only once.
Please do comment if you have any