Kotlin lateinit vs lazy

Rahul Sharma
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.

  1. lateinit (mutable)
  2. 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

  1. lateinit var can be initialised from anywhere, but lazy cannot.
  2. lazy instance can be stored any used in multiple areas.
  3. lateinit can be used only with val(immutable) and lazy can only be used with var(mutable).
  4. lazy is threadsafe
  5. lateinit doesn’t work with primitive
  6. lateinit can be initialised multiple time but lazy is allowed only once.

Please do comment if you have any

--

--