Scala variable
A variable is an easy-to-use placeholder that refers to the computer’s memory address, and it takes up a certain amount of memory space after it iscreated.
Based on the data type of the variable, the operating system allocates memory and decides what will be stored in reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or letters in these variables.
Variable declaration
Before we learn how to declare variables and constants, let’s look at some variables and constants.
Variable: the amount whose value may change during the running of the program is called variable. Such as: time, age.
Second, the constant whose value will not change during the running of the program is called constant. Such as: numeric value 3, character’A’.
In Scala, use the keyword “var” to declare variables and the keyword “val” to declare constants.
An example of declaring a variable is as follows:
var myVar : String = "Foo"
var myVar : String = "Too"
Variables are defined above myVar
, we can modify it.
An example of a declaration constant is as follows:
val myVal : String = "Foo"
The constant is defined above myVal
, it cannot be modified. If the program tries to modify the constant myVal
, the program will make an error in the compilation time.
Variable type declaration
The type of the variable is declared before the equal sign after the variable name. The syntax format for defining the type of a variable is as follows:
var VariableName : DataType [= Initial Value]
or
val VariableName : DataType [= Initial Value]
Variable type reference
Declaring variables and constants in Scala does not necessarily specify the data type, which is inferred from the initial value of the variable or constant without specifying the data type.
Therefore, if you declare a variable or constant without specifying the data type, you must give its initial value, otherwise an error will be reported.
var myVar = 10;
val myVal = "Hello, Scala!";
In the above example, myVar
will be inferred as Int
type, myVal
will be inferred as String
type.
Scala multiple variable declarations
Scala supports multiple variable declarations:
val xmax, ymax = 100 // xmax, ymax declare as100
If the method return value is a tuple, we can use the val
to declare a tuple:
scala> val pa = (40,"Foo")
pa: (Int, String) = (40,Foo)