[1] Scala Development Environment Setup Tutorial - Using IntelliJ IDEA [2] Scala Development Tutorial - Scala Basics: Data Types [3] Scala Development Tutorial - Scala Basics: Variables and Constants
In “[[2] Scala Development Tutorial - Scala Basics: Data Types](https://blog.renfei.net//en/posts/1003295 “[2] Scala Development Tutorial - Scala Basics: Data Types”)” we discussed data types. This article will discuss variables and constants in Scala. Before learning how to declare variables and constants, let’s first understand what variables and constants are:
-
- Variable: A quantity whose value may change during program execution is called a variable, e.g., time, age.
-
- Constant: A quantity whose value does not change during program execution is called a constant, e.g., the value 3, the character ‘A’.
In Scala, variables are declared with the keyword “var” and constants with the keyword “val”.
var myVar : String = "Foo"
var myVar : String = "Too"
Variable Type Declaration
The variable type is declared after the variable name and before the equals sign. The syntax for defining a variable’s type is as follows:
var VariableName : DataType [= Initial Value]
val VariableName : DataType [= Initial Value]
Variable Type Inference
When declaring variables and constants in Scala, you don’t necessarily have to specify the data type. When the data type is not specified, it is inferred from the initial value of the variable or constant. Therefore, if you declare a variable or constant without specifying a data type, you must provide an initial value, otherwise an error will occur.
var myVar = 10;
val myVal = "Hello, Scala!";
In the above example, myVar is inferred as type Int and myVal is inferred as type String.
Multiple Variable Declarations in Scala
Scala supports declaring multiple variables:
val xmax, ymax = 100 // xmax and ymax are both declared as 100
Author’s Notes
I came from a Java background and initially felt it was a bit like JavaScript with weak typing, but in fact Scala is still the same as Java—it’s just reversed: you write the variable name first, then a colon, then the type name. Automatic type inference just lets you be lazy and skip declaring the type; the type is inferred for you on first declaration, so if you don’t declare the type you must assign a value on first use.
As for whether to use val or var, it’s better to use val where possible, because it makes garbage collection and resource release more convenient. I think this was mentioned in one of the books by the creator of Scala.
