Google News
logo
Scala - Interview Questions
What is the difference between 'var', 'val', and 'lazy val' in Scala?
In Scala, `var`, `val`, and `lazy val` are used to declare variables, but they have different characteristics and behaviors:

1. `var` : A variable declared with the `var` keyword is mutable, meaning its value can be reassigned. It allows for changes to the variable's value throughout its lifetime.
   var x = 5
   x = 10​

   In this example, the variable `x` is declared using `var`, and its value is initially set to 5. Later, it is reassigned to 10 using the `=` operator. The value of a `var` can be modified multiple times.

2. `val`: A variable declared with the `val` keyword is immutable, meaning its value cannot be changed once assigned. It represents a read-only variable or a constant.
   val y = 7
   // y = 10   // Error: Reassignment to val​

   In this example, the variable `y` is declared using `val`, and its value is set to 7. Attempting to reassign a value to a `val` variable will result in a compilation error.
3. `lazy val`: A `lazy val` is similar to a `val`, but its initialization is deferred until it is accessed for the first time. It allows for lazy evaluation, meaning the value is calculated only when it is needed, and subsequent accesses use the precomputed value.
   lazy val z = {
     println("Initializing...")
     42
   }

   println(z)
   println(z)​

   Output :
   Initializing...
   42
   42​

   In this example, the variable `z` is declared as a `lazy val` and is assigned an expression block that computes the value `42`. The initialization block is executed only when `z` is first accessed. In this case, the initialization block prints "Initializing..." to the console. Subsequent accesses to `z` reuse the precomputed value without reevaluating the initialization block.

The choice between `var`, `val`, and `lazy val` depends on the requirements of your program and the desired behavior of the variable:

* Use `var` when you need a mutable variable that can be reassigned.
* Use `val` when you want an immutable variable or a constant that cannot be changed.
* Use `lazy val` when you want lazy evaluation, deferring the computation until the value is accessed for the first time.

Using `val` and `lazy val` for immutable variables can help improve code readability, maintainability, and reliability by reducing the potential for unintended modifications. Additionally, `lazy val` can be useful for optimizing performance by deferring expensive computations until they are actually needed.
Advertisement