Scala – Lazy Values

  • date 24th May, 2021 |
  • by Prwatech |
  • 0 Comments

In Scala Vals and Lazy vals are present . lazy keyword changes the val to get lazily initialized. Lazy initialization means that whenever an object creation seems costly, the lazy keyword can be stick before val. This gives it the advantage to get initialized in the first use i.e. the expression inbound is not evaluated immediately but once on the first access.

use case 1:

object prwatech {
// Main method 
    def main(args:Array[String]) 
    { 
        lazy val prwatech = {
               
            println ("Initialization for the first time")
            2
        }
        // Part 1
        println(prwatech)
           
        // Part 2
        print(prwatech)
    }   
}
Output 
Initialization for the first time
2
2

In the code above ‘prwatech’ was a lazy val and so for the first when it is accessed, it returned

Initialization for the first time

2

But for the second time when it is printed, it only returned

2

Because it is a cached result.

use case 2:

object prwatech {
 // Main method 
    def main(args:Array[String]) 
    { 
        var a = 3
           
        def fun() = { 
            a += 1; 
            a 
        }
           
        lazy val prwatech = Stream.continually( fun() )
           
        (prwatech take 5) foreach {
            x => println(x)
        }
    } 
}

output:

4
5
6
7
8

use case 3:

scala>var x = { println("x"); 15 }
scala>lazy val y = { println("y"); x + 1 }
scala>println("-----")
scala>x = 17
scala>println("y is: " + y)

Quick Support

image image