When val, var, lazy val and def constructs are Evaluated in Scala

Filed Under: Scala

Post Brief TOC

  • Introduction
  • Scala ‘val’ usage
  • How Scala ‘val’ is Evaluated?
  • Scala ‘var’ usage
  • How Scala ‘var’ is Evaluated?
  • Scala ‘def’ usage
  • How Scala ‘def’ is Evaluated?
  • How Scala ‘lazy val’ is Evaluated?
  • var Vs lazy val
  • Scala val,var,lazy val and def Constructs In-Brief

Introduction

In this post, we are going to discuss about some basic concepts of Scala Programming Language. Even though, it covers very basic concepts but they are very important to know.

We can answer some questions like What is val, var and def? What are the differences between them? When they are evaluated? What are the differences between val and lazy val?. These things are required to start working on Scala-Based Projects

Scala ‘val’ usage

In Scala, ‘val’ modifier is used to define constants. val means constant or immutable that means we cannot change it’s value once its created.

Example:-


scala> val name:String = "Scala"
name: String = Scala

scala> name
res2: String = Scala

scala> name = "Java"
:11: error: reassignment to val
       name = "Java"
            ^

Here, we can observe that reassignment to val is prohibited. That means val is used to define Immutable data.

How Scala ‘val’ is Evaluated?

In Scala, ‘val’ is used to define constants. It evaluates only once. They are evaluated at the time of definition only. Once its evaluated, it reuses same value for all references of it.

It does NOT evaluate every-time we access it.

We will explore this rule by using one simple example as shown below:

Example:-


object ValApp extends App{
  val number = { println("Constant number is initialized."); 99 }
  println("Before Accessing 'number' constant:")
  println(number + 1)
  println(number + 1)
  println(number + 1)
}

Output:-
Here I’m using all REPL commands for simplicity purpose only. We can test them using any Scala IDEs like Eclipse Scala IDE or IntelliJ IDE (My favourite IDE).


F:\>scalac ValApp.scala

F:\>scala ValApp
Constant number is initialized.
Before Accessing 'number' constant:
100
100
100

Here we can observe that “number” Constant is evaluated only once at the time of definition that’s why println output is printed before accessing the variable. Even though we have accessed number Constant three times, it’s initialized only once and printed “Constant number is initialized.” text only once.

Scala ‘var’ usage

In Scala, ‘var’ modifier is used to define variables. var means Variable or Mutable that means we can change it’s value once its created.

Example:-


scala> var name:String = "Scala"
name: String = Scala

scala> name
res0: String = Scala

scala> name = "Java"
name: String = Java

scala> name
res1: String = Java

Here, we can observe that reassignment to var is allowed. As var is used to define Mutable data, we can change its value once its created.

How Scala ‘var’ is Evaluated?

var is evaluated at the time of definition
It is evaluated only once

Example:-


object VarApp extends App{
  val number = { println("Variable number is initialized."); 99 }
  println("Before Accessing 'number' variable:")
  println(number + 1)
  println(number + 1)
  println(number + 1)
}

Output:-


F:\>scalac VarApp.scala

F:\>scala VarApp
Variable number is initialized.
Before Accessing 'number' variable:
100
100
100

Scala ‘def’ usage

In Scala, def is used to define functions or methods. A Method or Function may or may not have arguments and may or may not have return type.

Example:-


scala> def add(num1:Int, num2:Int): Int = num1 + num2
add: (num1: Int, num2: Int)Int

scala> add(11,22)
res2: Int = 33

As shown above, Method or Function is evaluated only we make a call to it.

How Scala ‘def’ is Evaluated?

In Scala, def is evaluated lazily. It is not evaluated at the time of definition. It is evaluated whenever we make a call to it. It is evaluated every-time we make a call to it.

Example:-


object DefApp extends App{
  def tax = {
    println("Function execution started.")
    1100
  }

  println(tax)
  println(tax)
  println(tax)
}

Output:-


Before making a cll to Function:
Function execution started.
1100
Function execution started.
1100
Function execution started.
1100

As shown above output, method or function is evaluated only when we make a call to it. Otherwise, it is not evaluated.

How Scala ‘lazy val’ is Evaluated?

As we know, val is used to define constants or Immutable Data. In the same way, we use “lazy val” to define Immutable data.

However, lazy val is evaluated lazily and only once. It is evaluated only once when we use it for first time.
It is not evaluated at the time of definition. It is not evaluated every-time we access it.

Example:-


object LazyValApp extends App{
  lazy val number = { println("Constant number is initialized."); 99 }
  println("Before Accessing 'number' constant:")
  println(number + 1)
  println(number + 1)
  println(number + 1) 
}

Output:-


Before Accessing 'number' constant:
Constant number is initialized.
100
100
100

Here I’m using same example of ValApp, but changed from “val” to “lazy val” that’s it.

If we observe this output, we can see that we are not seeing “Constant number is initialized.” output at the time of definition. We are seeing this message only at the time of first access. It’s displaying that message only once right. Cool!.

NOTE:- We cannot use “lazy” modifier for var. It’s allowed to use only for val.
Example:-


scala> lazy var a = 0
:1: error: lazy not allowed here. Only vals can be lazy
lazy var a = 0
     ^

var Vs lazy val

Here we will discuss some similarities and differences between val and lazy val constructs in Scala Language.

Similarities between val and lazy val constructs:-

  • Both are used to define constants or Immutable Data
  • Both are evaluated only once.

Differences between val and lazy val constructs:-

  • “val” is evaluated at the time of definition that means Eagerly.
  • “lazy val” is evaluated only when we access it that means Lazily.

Scala val,var,lazy val and def Constructs In-Brief

In previous sections, we have discussed about Scala val,var,lazy val and def Constructs in-detail with some simple and useful examples. Here are some bullet points to remember.

  • “val” is used to define Immutable data. It’s evaluated only once at the time of definition.
  • “var” is used to define Mutable data. It’s evaluated only once at the time of definition.
  • Both val and var are evaluated Eagerly.
  • “lazy val” is used to define Immutable data. It is evaluated only once when we access it for first time. That means it is evaluated Lazily.
  • “def” is used to define Methods or Functions. It is evaluated only when we access it and evaluated every-time we access it. That means it is evaluated Lazily.

NOTE:-In Scala, “by-name” arguments are evaluated/computed every time we access them. As it’s very big concept, we will discuss about it in a separate post soon.

That’s it all about Scala val,var, def and lazy val constructs usage and evaluation. We will discuss some more Scala concepts in my coming posts.

Please drop me a comment if you like my post or have any typo errors/issues/suggestions.

Comments

  1. Ajit says:

    Excellent tutorials .!!! Explanation with point to point wording giving better understanding.

  2. Giri says:

    Wow tutorial on scala basics. great man.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages