Kotlin Lazy Initialization Example

Lazy Initialization is a common pattern for delaying creation of an object, calculation of a value, or an expensive process until it’s accessed for the first time. It is helpful when the initialization process consumes significant resources and the data isn’t always required when the object is used. Kotlin provides a good solution for that with lazy function. In this tutorial, we’re gonna look at a Kotlin Lazy Initialization example.


>>> Refer to: JavaSampleApproach.com

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

Assume that we have a Person(name,books) class that lets us access a list of the books own by a person. Books list is stored in a database that we need time to access.

We want to load books on first access to the books property and do it only once.
It can be done with a delegated property:

lazy function (thread-safe by default) returns an object that has getValuemethod called.
– parameter of lazy is a lambda to initialize the value.

III. Practice

1. Helper Class

BookManager class handles processing data:

2. Class with delegated property

3. Run and check Result

Run the code below:

Check Result:

Add Comment