Scala variables


Variable is a convenient placeholder for referencing the computer 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 reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or letters in these variables.

Variable declaration

Before learning how to declare variables and constants, let’s first understand some variables and constants.

  • 1. Variables: A quantity whose value may change during the execution of a program is called a variable. Such as: time, age.

  • 2. Constants A quantity whose value does not change while the program is running is called a constant. For example: value 3, character 'A'.

In Scala, use the keyword "var" to declare variables and the keyword "val" to declare constants.

The example of declaring variables is as follows:

var myVar : String = "Foo"
var myVar : String = "Too"

The variable myVar is defined above and we can modify it.

Declare constant examples as follows:

val myVal : String = "Foo"

The constant myVal is defined above, and it cannot be modified. If the program attempts to modify the value of the constant myVal, the program will compile with an error.


Variable type declaration

The type of the variable is declared after the variable name and before the equal sign. The syntax format for defining the type of a variable is as follows:

var VariableName : DataType [=  Initial Value]

或

val VariableName : DataType [=  Initial Value]

Variable declaration does not necessarily require an initial value, the following is also correct:

var myVar :Int;
val myVal :String;

Variable type reference

In Scala It is not necessary to specify the data type when declaring variables and constants in . If the data type is not specified, the data type is inferred from the initial value of the variable or constant.

So, 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, and myVal will be inferred as String type.


Scala Multiple variable declarations

Scala supports the declaration of multiple variables:

val xmax, ymax = 100  // xmax, ymax都声明为100

If the method return value is a tuple, we can use val to declare one Tuple:

val (myVar1: Int, myVar2: String) = Pair(40, "Foo")

You can also not specify the data type:

val (myVar1, myVar2) = Pair(40, "Foo")