DEV Community

loizenai
loizenai

Posted on

Kotlin Lazy Initialization Example

https://grokonez.com/kotlin/kotlin-lazy-initialization-example

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.

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:


data class Person(val name: String) {

    val books by lazy { loadBooks(this) }
}
  • 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:

More at:

https://grokonez.com/kotlin/kotlin-lazy-initialization-example

Top comments (0)