When to use lateinit over lazy initialization in Kotlin?

Technology CommunityCategory: KotlinWhen to use lateinit over lazy initialization in Kotlin?
VietMX Staff asked 3 years ago

There are some simple rules to determined if you should use one or the other for properties initialisation:

  • If properties are mutable (i.e. might change at a later stage) use lateInit
  • If properties are set externally (e.g. need to pass in some external variable to set it), use lateinit. There’s still workaround to use lazy but not as direct.
  • If they are only meant to initialized once and shared by all, and it’s more internally set (dependent on variable internal to the class), then use lazy. Tactically, you could still use lateinit, but using lazy would better encapsulate your initialization code.

Also compare:

lateinit var by lazy
Can be initialized from anywhere the object seen from. Can only be initialized from the initializer lambda.
Multiple initialization possible. Only initialize single time.
Non-thread safe. It’s up to user to initialize correctly in a multi-threaded environment. Thread-safety by default and guarntees that the initializer is invoked by once.
Can only be used for var. Can only be used for val.
Not eligible for nonnull properties. Not eligible for nonnull properties.
An isInitialized method added to check whether the value has been initialized before. Property never able to un-initialized.
Not allowed on properties of primitive types. Allowed on properties of primitive types.