Scala - Variables

A variable is a convenient placeholder for referencing a computer memory address, which takes up a certain amount of memory after it is created.

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 those variables.

Variable declaration

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

  • One, variable: The amount by which a value may change during the running of a program is called a variable. Such as: time, age.
  • Second, the constant The amount whose value does not change during the running of the program is called a constant. Such as: the value 3, the character 'A'.

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

Declare variable instances as follows:

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

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

Declare a constant instance as follows:

val myVal : String = "Foo"

The above definition of 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 at compile time.

Variable Type Declaration

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

var VariableName : DataType [=  Initial Value]


val VariableName : DataType [=  Initial Value]

Variable type reference

Declaring variables and constants in Scala does not necessarily indicate the data type. In the absence of a data type, the data type is inferred from the initial value of the variable or constant.

So, if you declare a variable or constant without specifying a data type, you must give its initial value, otherwise you will get an error.

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

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

Scala Multiple Variable Declarations

Scala supports the declaration of multiple variables:

val xmax, ymax = 100  // xmax, ymaxDeclared as100

If the method return value is a tuple, we can declare a tuple using val :

scala> val pa = (40,"Foo")
pa: (Int, String) = (40,Foo)