Home » Scala

Scala lazy val

Scala | lazy val: In this tutorial, we are going to learn about the Scala lazy val. We will also see some important concepts about lazy val with examples.
Submitted by Shivang Yadav, on April 08, 2020

Scala | lazy val

Scala programming language allows the user to initialize a variable as a lazy val. A lazy variable is used when we need to save memory overheads while object creation. Using the lazy keyword, you can halt the initialization of the variable until the time it is first used or accessed in the code.

Program to illustrate lazy val

object myObject 
	def main(args:Array[String]) 
		lazy val newBlock = { 
			println ("This will be printed only in case of first initialization.") 

		println("The block is not initialized yet!")
		println("First Call : ")
		println("Second Call : ")


The block is not initialized yet!
First Call : 
This will be printed only in case of first initialization.
Second Call : 

As in the code, the block is initialized after the first print statement when it is called. The print statement of the newBlock will be printed only once. In the second call, it will return the string "Hello!" and does not print anything.

Comments and Discussions

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.