×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala lazy val (Scala Lazy Variable)

By IncludeHelp Last updated : October 09, 2024

What is 'lazy val' in Scala?

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.

How to initialize a variable as lazy?

To initialize a val as lazy, just use the lazy keyword at the beginning of the variable.

Syntax

lazy val newBlock = {
    println("Initialization.")
    "Hello!"
}

Scala example of lazy val initialization

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

    println("The block is not initialized yet!")

    println("First Call : ")
    println(newBlock)

    println("Second Call : ")
    println(newBlock)
  }
}

Output

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

Explanation

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.