Lateinit versus lazy
At first, lateinit var and by lazy {...} sound quite similar. However, there are significant differences between the two of them:
The
lazy {...}delegate can only be used for val properties;lateinitcan only be used forvarproperties.A
lateinitvar property can't be compiled into a final field, hence you can't achieve immutability.A
lateinit var property has a backing field to store the value, whereasÂlazy {...}creates a delegate object that acts as a container for the value once created and provides a getter for the property. If you need the backing field to be present in the class, you will have to uselateinit.The
lateinitproperty cannot be used for nullable properties or Java primitive types. This is a restriction imposed by the usage of null for uninitialized values.The
lateinit var property is more flexible when it comes to where it can be initialized. You can set it up anywhere the object is visible from. Forlazy{},it defines the only initializer for the...