178 total views, 2 views today
Welcome to Scala series. In this tutorial, you will learn about Scala lazy loading with examples.
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.
Lazy loading is a good programming practice to ensure data is loaded only when it is necessary.
Scala achieves using a keyword called lazy. This ensures the data is loaded in the variable only action is performed on the variable
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.
scala> lazy val x = (1 to 1600000).toList x: List[Int] = <lazy> scala> x.reduce(_ + _) res8: Int = 100545792
Thanks for reading Scala lazy loading with examples. please leave us a comment and give us a thumbs up!
Reference : Official documentation