At first, lateinit var and lazy {...} sound quite similar. However, there are significant differences between the two of them, listed as follows:
- The lazy {...} delegate can only be used for val properties; lateinit can only be used for var properties.
- A lateinit var property can't be compiled into a final field, and so 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 use lateinit.
- The lateinit property 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...