Scala lazy loading with examples

 178 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala lazy loading with examples.

What is Lazy loading?

It is a design concept in which you load or initialize an object when it is needed. To understand better let me explain you a scenario.

Consider you have a GUI page where you wanted to show millions of customer names on a button click or any action on the webpage.

Instead of loading entire data during webpage loading and keeping it in a cache, we can load data only on a button click. Because there is a possibility that the user may not click the button and data still resides in the cache without use.

In this case, there is no use of loading the data when it is not needed. Hence we are postponing the loading when an action is performed on the webpage.

So,

Lazy loading is a good programming practice to ensure data is loaded only when it is necessary.

Scala lazy loading

Scala achieves using a keyword called lazy. This ensures the data is loaded in the variable only action is performed on the variable

Example


scala> val x = 12;
x: Int = 12

scala> x * 10
res5: Int = 120
The above code allocates the memory and assigns 12 to x. This is an issue because This variable might be used in the program or not.
scala>  lazy val x =100;
x: Int = <lazy>

The above code does not allocate the memory. and the memory will be allocated during computation.

Another example

scala> lazy val x = (1 to 1600000).toList
x: List[Int] = <lazy>

scala> x.reduce(_ + _)
res8: Int = 100545792

Features of Lazy evaluation

  1. Lazy values are useful for delaying costly initialization instruction.
  2. Start time of application will not be slow
  3. Low use of memory

Thanks for reading Scala lazy loading with examples. please leave us a comment and give us a thumbs up!

Reference : Official documentation

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.