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:


package com.javasampleapproach.lazyinit

class BookManager {

	companion object {

		fun loadBooks(person: Person): List {

			println("Load books for ${person.name}")
			return listOf("Master Kotlin at JavaSampleApproach", "Be Happy to become Kotlineer")
		}

	}
}

2. Class with delegated property


package com.javasampleapproach.lazyinit

data class Person(val name: String) {
	
	val books by lazy { BookManager.loadBooks(this) }
}

3. Run and check Result

Run the code below:


package com.javasampleapproach.lazyinit

fun main(args: Array) {
	
	val person = Person("Andrien")
	
	println(person.books)
	
	println("--- call again ---")
	println(person.books)
}

Check Result:


Load books for Andrien
[Master Kotlin at JavaSampleApproach, Be Happy to become Kotlineer]
--- call again ---
[Master Kotlin at JavaSampleApproach, Be Happy to become Kotlineer]

One thought on “Kotlin Lazy Initialization Example”

  1. It’s perfect time to make a few plans for the future and it’s time
    to be happy. I have learn this publish and if I could I desire to
    suggest you few attention-grabbing issues or suggestions.
    Maybe you could write next articles referring to this article.
    I wish to read even more issues approximately it!

Leave a Reply

Your email address will not be published. Required fields are marked *