English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Variables are a convenient placeholder used to refer to the computer's memory address. After the variable is created, it will occupy a certain amount of memory space.
Based on the data type of the variable, the operating system will allocate memory and decide what will be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or letters in these variables.
Before learning how to declare variables and constants, let's first understand some variables and constants.
I. Variables: A quantity whose value may change during the execution of the program is called a variable. For example: time, age.
II. Constants A quantity whose value does not change during the execution of the program is called a constant. For example: numerical values 3, character 'A'.
In Scala, use the keyword "var" Declaration of variables, using the keyword "val" Declaration of constants.
Declaration of variables is shown as follows:
var myVar : String = "Foo" var myVar : String = "Too"
The above defines the variable myVar, which we can modify.
The following is an example of declaring a constant:
val myVal: String = "Foo"
The above defines the constant myVal, which cannot be modified. If the program tries to modify the value of the constant myVal, the program will report an error during compilation.
The type of a variable is declared before the variable name and after the equal sign. The syntax format for defining the type of a variable is as follows:
var VariableName: DataType [= Initial Value] or val VariableName: DataType [= Initial Value]
In Scala, it is not necessary to specify the data type when declaring a variable or constant. In the absence of a specified data type, the data type is inferred from the initial value of the variable or constant.
Therefore, if a variable or constant is declared without specifying a data type, it must provide an initial value, otherwise an error will occur.
var myVar = 10; val myVal = "Hello, Scala!"
In the above example, myVar will be inferred as Int type, and myVal will be inferred as String type.
Scala supports the declaration of multiple variables:
val xmax, ymax = 100 // xmax, ymax are declared as100
If a method returns a tuple, we can use val to declare a tuple:
scala> val pa = (40,"Foo") pa: (Int, String) = (40,Foo)