When I was building a tiny anime streaming helper app (think watchlist + recommendations), I had a singleton object storing all my video metadataâââbasically a Videos
object that held the list of episodes, their titles, and which season they belonged to.
At first glance, I just wrote:
object Episodes {
val all = listOf(
Episode("ep-1", "Narutoâs First Mission", 1),
Episode("ep-2", "Battle at the Bridge", 1),
Episode("ep-3", "Sasuke Awakens", 1)
)
}
But then I thoughtâââshould I make this lazy?
So I rewrote it like this:
object Episodes {
val all by lazy {
listOf(
Episode("ep-1", "Narutoâs First Mission", 1),
Episode("ep-2", "Battle at the Bridge", 1),
Episode("ep-3", "Sasuke Awakens", 1)
)
}
}
Turns out, this tiny by lazy
change led me down a rabbit hole of understanding how Kotlin properties actually work.
đ¤ What I Learned About object
and val
object
in Kotlin = true singleton.
The JVM actually creates one instance and keeps it forever.A simple
val = listOf(...)
inside an object is eagerly created once when the object is first referenced.Accessing it later just returns the same instanceâââit doesnât rebuild the list every time.
by lazy
only defers the creation until the first access, but after that, it also caches the value and returns the same reference.
So in practice:
đŻ When to Use by lazy
â Use it when:
The computation is expensive (e.g., reading a file, parsing JSON).
The object might never be used (avoid startup cost).
â Skip it when:
The data is tiny and always used (like my episode list).
You already reference it in
init { }
âââit will get forced anyway.You want simpler code with no first-access synchronization overhead.
đ§ Mental Model
Think of val = listOf(...)
like stocking all the anime DVDs on the shelf the moment your shop opensâââtheyâre ready to grab.
by lazy
is like keeping the DVDs in storage and only bringing them out the first time someone asks.
If people are guaranteed to ask for them every day, you just wasted a trip to the storeroom for no reason.
đĄ Takeaway for My Anime App
In my case, the app always needs the list of episodes (to build the table of contents and check for missing IDs).
So eager val
initialization made my code simpler and slightly fasterâââno lazy
wrapper, no synchronization, no surprises.
⨠Final Thought
Kotlin gives us great tools like by lazy
, but itâs not a magic performance boosterâââuse it where it actually saves you work, not just out of habit.