CodeGym /Courses /Kotlin SELF /by lazy — lazy evaluation and result caching

by lazy — lazy evaluation and result caching

Kotlin SELF
Level 32, Lesson 3
Available

1. Introduction

When you create an object, Kotlin honestly does everything needed for initialization: the constructor, init, property values. And sometimes that is great. But there are situations where a value may not be needed at all — or will be needed only in one scenario, and you do not want to spend time computing it “just in case”. This is where the idea of lazy initialization comes in: “compute it only on first access”.

A very everyday analogy: you do not fry potatoes every day “for later” if you are not sure you will even be home today. You start cooking when you are definitely hungry. lazy is roughly the same, just without the smell throughout the whole apartment.

In Kotlin there is a standard mechanism for delegated properties: val x by lazy { ... }. It computes the value once, on the first read, and then returns the already prepared result from the cache. This is exactly the behavior described in the documentation: the block runs on first access and the result is remembered; subsequent reads return the remembered value.

2. Syntax val x by lazy {...} and the meaning of by

At first glance the syntax looks a bit magical: why can’t you just write val x = ...? The secret is that lazy is a property delegate. That is, reading the property is “handed off” to a special object that knows how to compute the value and how to store it afterward.

The syntax is:


val name: Type by lazy {
    // computation
}

And the important practical rules here are very down-to-earth.

lazy is applied to val, because the whole point is that the value is computed once and then “locked in”. In the documentation this is described as “computed on first access and remembered”.

If you want “var and also lazy”, that is a different design: there you either need a computed property (get()), or an explicit cache with invalidation (those are already more advanced topics about architecture and responsibility).

The block inside lazy { ... } is a lambda, i.e., a piece of code that can be executed later. We have already seen lambdas before, so for now think of it as an “instruction deferred until later”.

Minimal example:

class AppInfo {
    val banner: String by lazy { "ExpenseTracker v0.1" }
}

fun main() {
    val info = AppInfo()
    println(info.banner) // ExpenseTracker v0.1
}

The funny thing is that this example does not really show the point of lazy at all (a string is cheap anyway). But it helps you get used to the syntax before we start lazily doing something truly useful.

3. When the lazy block runs and what is cached

The most common beginner question sounds like: “Okay, it’s lazy… but when exactly is it computed?” The answer is very specific: when you read the property for the first time. Not when the object is created, not at compile time, and not “when Kotlin decides”. Exactly on the first access of the form obj.x.

Here is a short demo where we intentionally add println to see the moment of computation:

class TokenProvider {
    val token: String by lazy {
        println("computing token...")
        "T-123"
    }
}

fun main() {
    val p = TokenProvider()

    println("before first read")
    println(p.token) // computing token... T-123
    println(p.token) // T-123
}

Notice the behavior: the message "computing token..." appears only once, and the second println(p.token) does not run the block anymore because the value is cached. It is like “brew coffee once — then drink from the mug”, except the coffee never runs out (which is already a bit of fantasy).

Formally, that is the lazy contract: the first call executes the lambda and remembers the result; subsequent calls return the remembered value.

4. lazy, computed property, and lateinit: similar, but solve different problems

It is very easy to mix up these three approaches because externally they are all about “a value that is not just a normal field”. But their meaning differs, and the right choice can save you hours of debugging.

Let’s compare them in one table:

Approach How it looks When the value appears Does it change over time Typical goal
Regular stored property
val x = ... / var x = ...
immediately when the object is created
val
— no,
var
— yes
simple data
Computed property
val x get() = ...
every time it is read depends on the data used a “computed view” without storage
lateinit var
lateinit var x: String
later, via assignment yes, it is a
var
non-null, but initialization after creation
val x by lazy { ... }
val x by lazy { ... }
on first read no (once and forever) defer computation and cache it

Now let’s show short examples so it becomes “tangible”.

Computed property: recomputed every time

Here we do not cache — this is not “laziness”, it is “dynamic computation”:

class CounterView(private var x: Int) {
    val doubled: Int
        get() = x * 2

    fun inc() { x++ }
}

fun main() {
    val v = CounterView(10)
    println(v.doubled) // 20
    v.inc()
    println(v.doubled) // 22
}

lateinit: the value will be assigned later, and that is your responsibility

class Config {
    lateinit var apiKey: String
}

fun main() {
    val c = Config()
    c.apiKey = "SECRET"
    println(c.apiKey) // SECRET
}

If you forget to assign it, you will get a runtime error. And that is fine: lateinit is the contract “initialize first, then use”.

lazy: computed once and remembered

class Greeting(private var name: String) {
    val hello: String by lazy { "Hello, $name" }
}

fun main() {
    val g = Greeting("Ann")
    println(g.hello) // Hello, Ann
}

And here comes a subtle point: if name is changed later (it is private here, but imagine it), hello will not update anymore because lazy caches.

5. lazy in the ExpenseTracker app

So that lazy does not remain a “trick for the sake of a trick”, let’s continue evolving a single learning app. Let it be a small console ExpenseTracker: we store expenses, can add them, and print simple reports.

Let’s start with a simple expense class where we protect invariants via require:

class Expense(
    val title: String,
    val cents: Int,
    val category: String
) {
    init {
        require(title.isNotBlank()) { "title must not be blank" }
        require(cents > 0) { "cents must be > 0" }
        require(category.isNotBlank()) { "category must not be blank" }
    }
}

Now let’s make a class that stores a list of expenses. Here we intentionally keep the list private and expose only safe methods (in the spirit of encapsulation).

class ExpenseBook {
    private val items: MutableList<Expense> = mutableListOf()

    fun add(expense: Expense) {
        items.add(expense)
    }

    fun size(): Int = items.size
}

So far it is boring, but a place for lazy will appear now.

Lazy help text for the CLI

Console apps usually have a help command that prints “how to use it”. This is text that most people never read… but when they do, it must be neat. And this is a good candidate for lazy: do not build a multi-line text in advance if the user did not ask for it.

class ConsoleHelp {
    val text: String by lazy {
        """
        Commands:
          add <title> <cents> <category>  — add an expense
          list                           — show expenses
          help                           — help
          exit                           — exit
        """.trimIndent()
    }
}

fun main() {
    val help = ConsoleHelp()
    println("App started")     // App started
    println(help.text)         // (help is printed here)
}

If the user never typed help, you do not “pay” for building the string at all. Yes, it is a micro-optimization, but it demonstrates the idea perfectly: lazy controls the moment of computation.

Lazy money formatter

A slightly more “adult” example: money formatting. We store amounts in cents (cents), but we want to display them nicely: "12.05".

Let’s make a separate formatting class:

class MoneyFormatter {
    fun format(cents: Int): String {
        val dollars = cents / 100
        val rest = (cents % 100).toString().padStart(2, '0')
        return "$dollars.$rest"
    }
}

Now suppose the formatter is “not always needed”. For example, you want to print a report only in the list command. Then you can keep it as lazy inside the app class:

class ExpenseApp {
    private val book = ExpenseBook()

    private val money: MoneyFormatter by lazy {
        println("MoneyFormatter created")
        MoneyFormatter()
    }

    fun addTestData() {
        book.add(Expense("Coffee", 350, "food"))
    }

    fun printCount() {
        println("items: ${book.size()}") // items: 1
    }

    fun printPriceExample() {
        println(money.format(350))       // MoneyFormatter created 3.50
    }
}

Here you will see that MoneyFormatter is created only when you first call printPriceExample() and actually access money.

6. The main lazy trap: the cache becomes stale when things change

This is where lazy stops being a “cute feature” and turns into something you must use consciously.

If a lazy value depends on mutable state, you risk getting a “nicely cached lie”. And it will be stable, fast, and confident — like a person who memorized the wrong answer and now has no doubts.

Bad example: we want “total expenses”, but the list of expenses grows. If we cache the sum via lazy, it will be correct only for the moment when it was first accessed.

class ExpenseBookBad {
    private val items: MutableList<Expense> = mutableListOf()

    val totalCents: Int by lazy {
        items.sumOf { it.cents }
    }

    fun add(expense: Expense) {
        items.add(expense)
    }
}

Problem scenario:

fun main() {
    val b = ExpenseBookBad()
    b.add(Expense("Coffee", 350, "food"))

    println(b.totalCents) // 350

    b.add(Expense("Sandwich", 650, "food"))
    println(b.totalCents) // still 350 (and that is already wrong)
}

lazy honestly does what it promised: “compute once and remember”. You just picked the wrong tool.

What is the correct approach? If the value must reflect the current state, it is better to use a computed property:

class ExpenseBook {
    private val items: MutableList<Expense> = mutableListOf()

    val totalCents: Int
        get() = items.sumOf { it.cents }

    fun add(expense: Expense) {
        items.add(expense)
    }
}

Now the sum is recomputed every time, but it is always up to date.

A practical rule sounds like this: lazy is great for values that either do not depend on changing state, or depend on something that does not change after initialization (configuration, text templates, prepared “heavy” objects that you do not want to recreate).

7. lazy nuances: side effects and thread safety

Reading a property (in an ideal world) is perceived as a “safe operation” that does not change state and does not surprise you. But lazy hides computation inside a property read — which is convenient, but requires discipline.

Side effects: why a “quiet getter” is a good habit

If inside lazy you do println, network requests, file writes, or “let’s create 10000 objects” — reading the property turns into a mini-quest. Sometimes that is acceptable (for example, a debug println in learning code), but in a real project you want such things under control.

Look at this example:

class ReportBuilder {
    val report: String by lazy {
        println("Building report...") // side effect
        "Report v1"
    }
}

If someone merely logs the object and accidentally touches report, you will suddenly start building a report “by itself”. Therefore a good habit is: a lazy block should be as “pure” as possible — compute and return a value, without surprises. And if it does have side effects, at least make them conceptually expected (for example, initializing a heavy cache).

Thread safety: what matters without diving into details

Sometimes people ask: “Is lazy thread-safe?” Very briefly: by default lazy is implemented so that the computation is performed once in a multithreaded environment (i.e., synchronization is provided). In the documentation this is described as the default behavior, and the modes you can choose via the LazyThreadSafetyMode parameter are explained.

But the key practical point for us right now is: in a typical learning console app that runs on a single thread, the default “regular lazy” is almost always enough. The main thing is to understand the contract “once, on first read”.

One more nuance: if the lazy block throws an exception, the value will not be successfully cached, and on the next attempt to read the property it will try to compute again (because there was no “successful result”). This is useful to remember if inside lazy you do require(...) or something else that can fail: the failure happens not when the object is created, but on the first property read — i.e., later — and sometimes that is unexpected.

8. Typical mistakes when working with by lazy

Mistake #1: trying to make a var with lazy.
Sometimes you want to write var x by lazy {...} because “well, I want it to be lazy”. But the whole point of lazy is that the value is computed once and fixed. If you need a mutable value, it is not a lazy task: most often a computed property (get() = ...) or a regular var with explicit update management will fit.

Mistake #2: caching via lazy something that depends on changing data.
A classic trap is caching a sum, status, or report that must change when elements are added to a list. lazy runs once, and then returns the old result forever. If the value must always be current, use a computed property or recompute it in state-mutating methods.

Mistake #3: hiding heavy and/or “noisy” logic inside a property read.
When lazy does a lot of work, reading the property suddenly becomes an “operation with side effects”. That makes the code harder to understand: a developer reads obj.x and does not expect half a second of computations. It is better to keep the lazy block small and move the complex part into a function that you call inside lazy (at least then you see the operation name).

Mistake #4: expecting lazy to “speed up the program always”.
lazy is not a universal optimization. It helps defer computation until the moment it is truly needed, and avoid repeating it. But if a value is needed always and immediately, lazy can even add a small overhead. Use it as a design tool to control when computation happens, not as a “magic performance button”.

Mistake #5: quietly tying lazy to external mutability.
If lazy uses variables that may change before the first access, the result will depend on “when exactly it was first read”. Sometimes that is acceptable logic, but more often it is a source of weird bugs. A good style: make lazy depend either on immutable configuration or on data you consider stable by the time of first use.

1
Task
Kotlin SELF, level 32, lesson 3
Locked
Lazy Greeting
Lazy Greeting
1
Task
Kotlin SELF, level 32, lesson 3
Locked
Help command
Help command
1
Task
Kotlin SELF, level 32, lesson 3
Locked
Session ID
Session ID
1
Task
Kotlin SELF, level 32, lesson 3
Locked
Current basket
Current basket
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION