1.

Differentiate between lateinit and lazy initialisation. Explain the cases when you should use lateinit and when you should use lazy initialisation.

Answer»

Following are the differences between lateinit and lazy initialisation:-

lateinitlazy initialisation
The main PURPOSE is to delay the initialisation to a later point in time.The main purpose is to initialise an object only when it is used at a later point in time. Also, a single COPY of the object is maintained throughout the program. 
It's possible to initialise the object from anywhere in the program.Only the initializer lambda can be used to initialise it.
Multiple initializations are possible in this case.Only a single initialisation is possible in this case.
It's not thread-safe. In a multi-threaded system, it is up to the user to correctly initialise.Thread-safety is enabled by default, ensuring that the initializer is only called once.
It works only with var.It works only with val.
The isInitialized method is added to verify if the value has previously been initialised.It is impossible to uninitialize a property.
Properties of PRIMITIVE TYPES are not allowedAllowable on primitive type properties.

There are a few easy principles to follow when deciding whether to use lateinit or lazy initialisation for property initialization:

  • Use lateInit if properties are mutable (i.e., they may change later).
  • Use lateinit if properties are set externally (for example, if you need to pass in an external VARIABLE to set it). There is still a way to use lazy, but it isn't as obvious.
  • If they're only meant to be initialised once and shared by everybody, and they're more internally set (depending on a class variable), then lazy is the way to go. We could still use lateinit in a tactical sense, but utilising lazy initialisation would better encapsulate our initialization code.


Discussion

No Comment Found