Home » Scala language

var keyword with example in Scala

Scala var keyword usage and syntax: Here, we are going to learn about the var keyword in Scala, how to use var keyword in a Scala program? Explained example to use Scala var keyword.
Submitted by Shivang Yadav, on June 11, 2019

Scala 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 define mutable variables in Scala 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 program to demonstrate example of 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 )
      }
   }

Output

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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.