By Lazy🎉

Sümeyra Özuğur-En
2 min readDec 5, 2022

The creation of objects is an expensive process for systems. Once an object is created, its properties are created in the constructor. Obviously, these occupy memory space. In general, when the more memory space is occupied, the longer it will take for the process to complete.

Well, what if the object is not created immediately upon creation, but only when it is called, and then even if the property we call is kept in memory, instead of re-creating in the places we call it, it returns the memory value?

Here is the by lazy function. Let’s go through a small example to understand better.

val message by lazy{
say("Hello")
"Hi"
}

fun say(s: String) {
println(s)
}

fun main(){
println(message)
println(message)
println(message)
}
//Output
Hello
Hi
Hi
Hi

So what exactly is going on here? Don’t be panic!!, I’m telling you right now.

There is a “message” variable in the block, which can be accessed by calling it. Values of output(”Hello” and “Hi”) ​​are thus displayed on the screen. This block does not work when the second and third “message” value is written. Because this worked before and our “message” value was assigned as “Hi”. From now on, only the value of this will appear in every running “message”. So, the block doesn’t work anymore we get the value in memory.

Lazy part is done. I hope everything is clear so far. Finally, let’s talk about the differences between lateinit and lazy.

Lazy vs Lateinit

✅ Lazy is used with the “val” keyword, while lateinit is used with the “var” keyword.

✅ While we can call functions inside a lazy function, lateinit cannot.

✅ While lateinit cannot be used with primitives, we can use lazy.

✅ While lateinit can not be used with nullable, lazy can.

✅ Lazy is initialised when it will be called the first time. Then it uses value in memory. After lateinit is initialized, it gets recreated wherever it is called

⭐As Bill Gates said, lazy is important . Take care and see you in the next article.

Dipnot: To read this content in Turkish, click here.

--

--