Property initialization using "by lazy" vs. "lateinit"
Solution 1:
Here are the significant differences between lateinit var
and by lazy { ... }
delegated property:
-
lazy { ... }
delegate can only be used forval
properties, whereaslateinit
can only be applied tovar
s, because it can't be compiled to afinal
field, thus no immutability can be guaranteed; -
lateinit var
has a backing field which stores the value, andby lazy { ... }
creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, uselateinit
; -
In addition to
val
s,lateinit
cannot be used for nullable properties or Java primitive types (this is because ofnull
used for uninitialized value); -
lateinit var
can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class.by lazy { ... }
, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, uselateinit
. -
Initialization
by lazy { ... }
is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using anotherlazy
overload). In the case oflateinit var
, it's up to the user's code to initialize the property correctly in multi-threaded environments. -
A
Lazy
instance can be saved, passed around and even used for multiple properties. On contrary,lateinit var
s do not store any additional runtime state (onlynull
in the field for uninitialized value). -
If you hold a reference to an instance of
Lazy
,isInitialized()
allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can useproperty::isInitialized
since Kotlin 1.2. -
A lambda passed to
by lazy { ... }
may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.
Also, there's another way not mentioned in the question: Delegates.notNull()
, which is suitable for deferred initialization of non-null properties, including those of Java primitive types.
Solution 2:
lateinit vs lazy
-
lateinit
i) Use it with mutable variable[var]
lateinit var name: String //Allowed lateinit val name: String //Not Allowed
ii) Allowed with only non-nullable data types
lateinit var name: String //Allowed
lateinit var name: String? //Not Allowed
iii) It is a promise to compiler that the value will be initialized in future.
NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.
-
lazy
i) Lazy initialization was designed to prevent unnecessary initialization of objects.
ii) Your variable will not be initialized unless you use it.
iii) It is initialized only once. Next time when you use it, you get the value from cache memory.
iv) It is thread safe(It is initialized in the thread where it is used for the first time. Other threads use the same value stored in the cache).
v) The variable can only be val.
vi) The variable can only be non-nullable.
Solution 3:
Additionnally to hotkey
's good answer, here is how I choose among the two in practice:
lateinit
is for external initialisation: when you need external stuff to initialise your value by calling a method.
e.g. by calling:
private lateinit var value: MyClass
fun init(externalProperties: Any) {
value = somethingThatDependsOn(externalProperties)
}
While lazy
is when it only uses dependencies internal to your object.
Solution 4:
Very Short and concise Answer
lateinit: It initialize non-null properties lately
Unlike lazy initialization, lateinit allows the compiler to recognize that the value of the non-null property is not stored in the constructor stage to compile normally.
lazy Initialization
by lazy may be very useful when implementing read-only(val) properties that perform lazy-initialization in Kotlin.
by lazy { ... } performs its initializer where the defined property is first used, not its declaration.