Easy Tutorial
❮ Scala Classes Objects Scala Closures ❯

Scala Variables

Variables are convenient placeholders used to reference computer memory addresses, and once created, they 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.

Variable Declaration

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

In Scala, variables are declared using the keyword "var", and constants are declared using the keyword "val".

Example of declaring a variable is as follows:

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

The above defines the variable myVar, which we can modify.

Example of declaring a constant is as follows:

val myVal : String = "Foo"

The above defines the constant myVal, which cannot be modified. If the program attempts to change the value of the constant myVal, the program will report an error during compilation.


Variable Type Declaration

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

var VariableName : DataType [= Initial Value]

or

val VariableName : DataType [= Initial Value]

Variable Type Inference

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

Therefore, when declaring a variable or constant without specifying the data type, it is necessary to provide its initial value, otherwise an error will occur.

var myVar = 10;
val myVal = "Hello, Scala!";

In the above example, myVar will be inferred as the Int type, and myVal will be inferred as the String type.


Scala Multiple Variable Declaration

Scala supports the declaration of multiple variables:

val xmax, ymax = 100  // xmax, ymax are both declared as 100

If the method returns a tuple, we can use val to declare a tuple:

scala> val pa = (40,"Foo")
pa: (Int, String) = (40,Foo)
❮ Scala Classes Objects Scala Closures ❯