-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Programming Kotlin
By :

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; lateinit
can only be used for var
properties.
A lateinit
var 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 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 comes to where it can be initialized. You can set it up anywhere the object is visible from. For lazy{},
it defines the only initializer for the...