Compilers allocate memory and decide what can be stored in reserved memory based on variables' data types. As a result, you can store integers, decimals, or characters in variables by assigning different data types.
They can be defined as value. It is a variable that can change the value and this is called a mutable variable.
var myVar : String = "CodeXposer"
This means that it is a variable that cannot be changed and this is called an immutable variable.
val myVal : String = "CodeXposer"
Variable Data Types
val or var VariableName : DataType = [Initial Value]
var myVar :Int;
val myVal :String;
Variable Type Inference
By assigning a value to a variable, the Scala compiler can determine the variable's type. This is called variable type inference.
var myVar = 10;
val myVal = "CodeXposer";
Multiple assignments
val (myVar1: Int, myVar2: String) = Pair(90, "CodeXposer")
val (myVar1, myVar2) = Pair(90, "Foo")
Variable Scope
Depending on their use, Scala variables can have three different scopes.
Fields - variables that belong to an object (can be defined by var or val)
Method Parameters - used to pass the value inside a method, when the method is called. (defined by val keyword)
Local Variables - variables declared inside a method (can be defined by var or val)
Comments