Home » Scala language

Difference between var and val keywords in Scala

Scala var vs val keywords: Points of similarities and differences between var and val keywords in Scala. Uses, example code, and application of var and val keywords.
Submitted by Shivang Yadav, on June 17, 2019

The initialization of variables in Scala is done using three keywords def, var, and val. The keywords var and val both are used to assign memory to variables at the running only. The difference is in the mutability of variables that are initialized using these keywords.

var keyword initializes variables that are mutable, and the val keyword initializes variables that are immutable.

Differences between var and val keywords in Scala

var Keyword val Keyword
Used to initialize variables in Scala. Used to initialize read only variables in Scala.
Variables are initialized at compile time. Variables are initialized at compile time
Variable defined are mutable variables. Variables defined are immutable variables.
Values are not constant for var variables. Values are constant for val variables.
Changing the value of the variable in the program does not cause an error. Changing the value of the variable is an error in the case of var declaration.
Example, Counter, loop variable, sum, etc. Example, name, id, constants.
Syntax: var myVar = 32; 
Syntax: val myVal = 43; 

Both declarations are valid in Scala and you can you both in the program together if needed. Both keywords support all data types initialization in both explicit and automatic way.

The concept of mutability is from java’s String that is immutable. But in Scala you can make any variable immutable this gives the user a way to restrict some variable usage to read-only.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




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.