What is a Lazy Stored Property and when to use it?

Simran Kaur
3 min readDec 21, 2021

--

Lazy Properties are those properties whose value is not calculated until we use them. This is the definition you can get almost everywhere online, but what does it actually mean? Let me break it to you.

We all know about computed properties, right? Whenever we want to do any calculation we make use of them and every single time when it is initialized its value is calculated. But in the case of Lazy stored properties, its value is not calculated at the initialization but is only calculated when we actually use that property or in simple words we can say that memory is not allocated to the property unless we use it.

Let's see an example:

I have created one class that has a static method called calculate, which does nothing more than doing some iteration and printing the number. We will use this method to do some random calculations to understand Lazy Stored Properties better.

Next, I have created another class that has some properties -> employeeName, employeeId and salary where salary is a computed property that calculates the salary of the employee.

Now, I have created one object for the class.

Run the project and you’ll notice that the salary property is calculated first and then the object is initialized. Using a computed property is not wrong here but what if there is some big calculation going on, that will slow down your project and no one would want that, right?. That is where we use Lazy Stored Properties.

Now, just add the lazy keyword in front of salary property and run the project again. Notice how this time there is no calculation happening and the object is initialized immediately? This is the magic of Lazy Stored Properties.

Go ahead and use the salary property now and run the project:

You will now see that the value is calculated.

Another example would be if a property’s value is dependent on some other values.

An example would be:

Here, in order to calculate salary, we need to know the name and id of the employee, so here salary’s value is dependent on the other two properties.

That’s all about Lazy Stored Properties. I hope now you got a better understanding of them.

Thanks for reading. :) Do give this a like.

You can contact me at:

LinkedIn: https://www.linkedin.com/in/simranjeet-kaur-204015128/

Email- Id: simrankaurg555@gmail.com

--

--