A variable is an easy-to-use placeholder that refers to the computer’s memory address, and it takes up a certain amount of memory space after it iscreated.
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 these variables. Before we learn how to declare variables and constants, let’s look at some variables and constants. Variable: the amount whose value may change during the running of the program is called variable. Such as: time, age. Second, the constant whose value will not change during the running of the program is called constant. Such as: numeric value 3, character’A’. In Scala, use the keyword “var” to declare variables and the keyword “val” to declare constants. An example of declaring a variable is as follows: Variables are defined above An example of a declaration constant is as follows: The constant is defined above The type of the variable is declared before the equal sign after the variable name. The syntax format for defining the type of a variable is as follows: Declaring variables and constants in Scala does not necessarily specify the data type, which is inferred from the initial value of the variable or constant without specifying the data type. Therefore, if you declare a variable or constant without specifying the data type, you must give its initial value, otherwise an error will be reported. In the above example, Scala supports multiple variable declarations: If the method return value is a tuple, we can use the 8.6.1. Variable declaration #
var myVar : String = "Foo"
var myVar : String = "Too"
myVar
, we can modify it.val myVal : String = "Foo"
myVal
, it cannot be modified. If the program tries to modify the constant
myVal
, the program will make an error in the compilation time. 8.6.2. Variable type declaration #
var VariableName : DataType [= Initial Value]
or
val VariableName : DataType [= Initial Value]
8.6.3. Variable type reference #
var myVar = 10;
val myVal = "Hello, Scala!";
myVar
will be inferred as
Int
type,
myVal
will be inferred as
String
type. 8.6.4. Scala multiple variable declarations #
val xmax, ymax = 100 // xmax, ymax declare as100
val
to declare a tuple:scala> val pa = (40,"Foo")
pa: (Int, String) = (40,Foo)