Lazy Initialization

This Atom is Under Construction

So far, you’ve learned two ways to initialize properties.

  1. Store the initial value when you define the property.

  2. Define a custom getter that computes the property for each access.

This atom explores a third use case: properties with expensive initialization. For example, a property might require network requests or database access during initialization. This can produce two problems:

  1. Long application start-up time.

  2. Performing unnecessary work if that property is never used.

This happens frequently enough that Kotlin includes lazy properties to provide a built-in solution. A lazy property is initialized when it’s first used, rather than when it’s created. If we never use a lazy property, it never performs that expensive initialization.

The concept of lazy properties isn’t unique to Kotlin. “Laziness” can be implemented within other languages, whether or not they provide direct support. Kotlin provides a consistent, recognizable idiom for lazy properties using Property Delegation (the by keyword). With a lazy property, by is followed by a call to lazy():

val lazyProperty by lazy { initializer }

End of sample. See for full early-access book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.