Home »
Scala
Difference between var and val keywords in Scala
By IncludeHelp Last updated : October 09, 2024
The initialization of variables 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;
|
Conclusion
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.