lazy Property in Kotlin

Suneet Agrawal
2 min readDec 3, 2021

--

Object creation is a heavy process. When we create a class object, all the public and private properties of that class are initialised inside the constructor. Every variable inside a class initialisation requires a certain amount of time to allocate the memory on the heap and hold its reference on the stack. The more variables, the more time it may take but since the time is in microseconds or even less, it’s not observable.

This post was originally posted at https://agrawalsuneet.github.io/blogs/lazy-property-in-kotlin/ and reposted on Medium on 03rd Dec 2021.

Sometimes we don’t need all the objects to be initialised during the class object creation itself.
There can be two reasons for that.

  1. That object/property/variable is dependent on another object to initialise first and use its reference.
  2. The flow is such that we need that object only in a certain condition.

In Kotlin, we have certain features which can help us in delaying that object initialisation as per the requirement.
One way to do that is by using lateinit Property where we just declare the object/property and its type but didn’t initialise it.

The drawback with lateinit var is

  1. Its var that means it’s mutable
  2. We (developer) need to remember to initialise it.
  3. We can’t have a custom getter to the lateinit property

We have another way also to delay the initialisation of a property ie by using lazy initialisation.

lazy initialisation is a delegation of object creation when the first time that object will be called. The reference will be created but the object will not be created. The object will only be created when the first time that object will be accessed and every next time the same reference will be used.

The basic initialisation of a User class object by using lazy will look like below

data class User(val id : Long,
val username : String)

val user : User by lazy {
//can do other initialisation here
User(id = 1001, username = "ballu")
}

Please continue reading at https://agrawalsuneet.github.io/blogs/lazy-property-in-kotlin/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--