var Keyword

‘var’ is used to declare mutable variables. Once it is defined, the value of a variable declared with ‘var’ can be reassigned.

Syntax:

var variableName: DataType = value

Example:

Scala
object Main {
    def main(args: Array[String]): Unit = {
        var age: Int = 25
        println(age)    
      
        // Reassignment allowed
        age = 30         
        println(age)
    }

Output:

After running above it initializes age with the value 25, prints it, then reassigns age to 30 and prints it again. So, the output will be 25 followed by 30.

var-keyword-output

Difference Between var, val, and def Keywords in Scala

Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language that also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM (Java Virtual Machine). Scala stands for Scalable language. It also provides Javascript runtimes. Scala is highly influenced by Java and some other programming languages like Lisp, Haskell, Pizza, etc. This article focuses on discussing the differences between var, val, and def keywords in Scala.

Table of Content

  • var Keyword
  • val Keyword
  • def Keyword
  • Difference between var, val and def Keywords
  • Conclusion

Similar Reads

var Keyword

‘var’ is used to declare mutable variables. Once it is defined, the value of a variable declared with ‘var’ can be reassigned....

val Keyword

Scala’s ‘val’ is similar to a final variable in Java or constants in other languages. It’s also worth remembering that the variable type cannot change in Scala....

def Keyword

‘def’ keyword is used to define methods (functions). Methods defined with ‘def’ are evaluated each time they are called....

Difference between var, val and def Keywords

Features ‘var’ Keyword ‘val’ Keyword ‘def’ Keyword Mutability Mutable Immutable Not Applicable Reassignment Allowed Not Allowed Not Applicable Usage For declaring variables For declaring constants For declaring methods Syntax var name: Type = value val name: Type = value def methodName(params): ReturnType = { body } Memory Allocation Allocated at declaration Allocated at declaration Allocated at invocation Performance May incur overhead Minimal overhead May incur overhead Execution Time At each assignment Once at declaration At each invocation Lazy Evaluation Not supported Not supported Supported with lazy ‘val’ Example var x: Int = 5 val y: String = “Hello” def add(x: Int, y: Int): Int = { x + y }...

Conclusion

In short, the ‘val ‘and ‘var’ are evaluated when defined, while ‘def’ is evaluated on call. Also, ‘val’ defines a constant, a fixed value that cannot be modified once declared and assigned while ‘var’ defines a variable, which can be modified or reassigned....