Difference Between var, val, and def Keywords



Keywords var, val, and def in Scala are used to declare and use variables, constants, and methods. The var is a variable that can change its value. So it is mutable and the value of a var can be reassigned. Whereas, val is used to declare constants. Once assigned, a val cannot change its value. So it is immutable. This is similar to final variables in Java where variable type remains constant. The def keyword is used to declare methods. Unlike var and val, which are evaluated when they are defined. The def is evaluated each time it is called. We have discussed these three keywords in this post.

Mutable Variables (var)

A variable declared with the keyword var is mutable meaning its value can change during the program's execution. This is useful when you need a variable that can be updated.

Syntax

The syntax of var variable is -

var myVar: String = "Foo"

Example

object Demo {
   def main(args: Array[String]) = {
      var myVar: Int = 10
      println(myVar)
      
      myVar = 20
      println(myVar)
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10
20

Here, myVar is a mutable variable of type Int. Its value is initially set to 10 and later changed to 20.

Immutable Variables (val)

A variable declared with the keyword val is immutable. So its value cannot be changed once assigned. This is similar to a constant.

Syntax

The syntax of the val variable is -

val myVal: String = "Foo"

Example

object Demo {
   def main(args: Array[String]) = {
      val myVal: String = "Hello, Scala!"
      println(myVal) 
      
      // Uncommenting the next line will cause a compilation error
      // myVal = "New Value"
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Hello, Scala!

Here, myVal is immutable. Once set to "Hello, Scala!", it cannot be reassigned.

Methods (def)

Methods in Scala are declared using the def keyword. These represent functions and are evaluated each time they are called.

Syntax

The syntax to declare a method is -

def methodName(parameterList): ReturnType = { methodBody }

Example

object Demo {
   def add(x: Int, y: Int): Int = x + y

   def main(args: Array[String]) = {
      val result = add(3, 5)
      println(s"Result: $result")
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Result: 8

Here, we declared the add method using the def keyword. The add method takes two integers and returns their sum. It is evaluated each time it is called.

Lazy Values

Lazy values in Scala are defined using lazy val. Their initialization is deferred until these are accessed for the first time. These can be used for expensive computations.

Example

object Demo {
   lazy val lazyVal: Int = {
      println("Computing lazy value")
      42
   }

   def main(args: Array[String]) = {
      println("Before accessing lazyVal")
      println(lazyVal)
      println(lazyVal)
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Before accessing lazyVal
Computing lazy value
42
42

Here, lazyVal is not computed until it is first accessed. So it is delaying the print statement inside its initialization block.

Variable Type Inference

When you assign an initial value to a variable, the Scala compiler can infer the type of the variable based on the value assigned. This is called variable type inference.

Syntax

The syntax of variable type inference is -

var myVar = 10 // myVar is inferred to be of type Int
val myVal = "Hello, Scala!" // myVal is inferred to be of type String

Example

object Demo {
   def main(args: Array[String]) = {
      var myVar = 10
      val myVal = "Hello, Scala!"
      
      println(myVar)
      println(myVal)
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

10
Hello, Scala!

Here, myVar is inferred to be of type Int and myVal is inferred to be of type String.

Multiple Assignments

Scala supports multiple assignments. If a code block and method returns a tuple, the tuple can be assigned to a val variable.

Syntax

The syntax for using multiple assignments is -

val (myVar1: Int, myVar2: String) = (40, "Foo")

Example

object Demo {
   def main(args: Array[String]) = {
      val (myVar1, myVar2) = (40, "Foo")
      println(myVar1)
      println(myVar2)
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

40
Foo

Here, myVar1 and myVar2 are assigned the values 40 and "Foo" respectively.

Differences Between def, var & val in Scala

The following table shows the key differences between def, var, and val keyword based on the various aspects −

Feature var val def
Mutability Mutable Immutable Not applicable
Reassignment Allowed Not allowed Not applicable
Usage Variables Constants Methods
Syntax var x: Type = value val x: Type = value def methodName(params): Type
Evaluation Time At declaration At declaration At each invocation
Memory Allocation At declaration At declaration At each invocation
Lazy Evaluation Not supported Supported with lazy val Not supported
Example var x = 10 val y = 20 def add(a: Int, b: Int) = a + b
Similar to Mutable variables in Java Final variables in Java Functions in Python

Summary

  • The var is used for mutable variables that can change value.
  • The val is used for immutable variables that cannot change value.
  • The def is used for defining methods that are evaluated each time they are called.
  • The lazy val can be used for deferred initialization of values.
  • So it provides an efficient way to handle expensive computations.
Advertisements