Scala var Keyword

In this tutorial, we will learn about the var keyword with example in Scala. By Shivang Yadav Last updated : April 02, 2023

The 'var' Keyword

The var Keyword in scala is used to declare variables. As Scala does not require explicit declaration of data type of the variable, var keyword is used. The variable declared using the var keyword as mutable variables.

Mutable Variables are those variable whose value can be changed in the program, these are used when you need variables which are updated as per the logic of the program. Example of some mutable variables are counters, loop variables, sum, etc.

Syntax to declare variables using var keyword

var I = 102;
var H : string = "IncludeHelp";

Syntax Explanation

In the first on we have declared a variable I using var keyword. This can be changed in future. The value is 102 so scala will itself make it an int type. In the second one we have explicitly declared the data type of the variable. This is a good practice and you know the limitation of the initialization. It declares the var H as a string using variable. The value will be strictly string and if we stored a number in it will be stored as a string.

Using var keyword you can define variables of all data types in Scala. The value of variables declared using the var keyword can be changed at any point in the program.

Scala example of the var keyword

// Program that displays usage of var keyword in Scala

object VarKeyword {
      def main(args: Array[String]) {
          var myVar = 52;//Variable Initialized with value 52 
          print("Value of my myVar =" + myVar + "\n")
          myVar = myVar + 6; // Value changes to 52+6
          print("Changed Value of myVar = " + myVar )


Value of my myVar =52
Changed Value of myVar = 58

Example Explanation

The code displays use of var keyword in real world program. The variable myVar's value changes in the program.

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.