Latest web development tutorials

Scala variables

Variable is a convenient placeholder for reference computer memory addresses, will occupy some memory space after the variable is created.

Based on the data type of the variable, the operating system memory allocation and decide what will be stored in the reserved memory. Therefore, the allocation of different data types, you can store an integer, decimal or letters in the word through these variables to the variable.

Variable declaration

Before learning how to declare variables and constants, we start to understand some of the variables and constants.

  • A variable: the program is running in an amount likely to change its value is called variable. Such as: time, age.
  • Second, the program is running at a constant whose value does not change the amount of known constants. Such as: the value 3, the character 'A'.

In Scala, use the keyword"var" to declare a variable, use the keyword "val"declared constants.

Examples of variable declaration as follows:

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

Above defines a variable myVar, we can modify it.

Declare a constant examples are as follows:

val myVal : String = "Foo"

Above defines constants myVal, it can not be changed. If a program attempts to modify the value of the constant myVal, the program will be given at compile time.


Variable type declaration

Type of a variable declared before the variable name after the equal sign. Define the variable type syntax 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 true:

var myVar :Int;
val myVal :String;

Variable types referenced

In Scala declare variables and constants do not have to specify the type of data, in the absence of specified data type, the data type is in the initial value of the variable or constant inferred.

So, if you declare a variable or constant in the absence of the specified data type must be given its initial value, otherwise it will error.

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

The above example, myVar is inferred to be of type Int, it myVal be inferred as a String type.


Scala plurality of variable declarations

Scala supports declare multiple variables:

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

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

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

You can also not specify a data type:

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