In this lesson, we would learn about variables in Scala.
Variables in Scala have the same meaning as in Java: they are memory locations. So when a variable is declared, a memory space is reserved for them.
The size of the memory space allocated for a variable would depend on the data type of the variable.
1. Declaring a Variable
There are two ways variables can be declared in Scala
- val – in this case, the variable is declared as a constant value and cannot be changed
- var – using the var keyword, you can declare a variable that can change in value. This is called mutable variable.
Examples are given below:
var name: String = "Kindson" //mutable variable val department: String = "ICT"
Note from the variable declaration that the variables are declared and initialized the same time. The data type of the variable is specified after the name of the variable.
2. Type Inference
In Scala, you can also assign a value to a variable without specifying a data type. You just need to omit, the data type that comes after the colon (:). When you do this, the Scala compiler could infer the data type of the variable based on the value assigned to it. This is known as type inference. Some examples are:
var name = "The Tech Pro" val score = 99 var grade = 'A'
3. Multiple assignments
You can assign values to more than on variable in the same statement. For example, an expression could return a tuple, which can then be assigned to a val variable. An example is given below:
val (score: Int, course: String) = Pair(98, "Math")
In this example, the value 98 is assigned to the variable score while the value “Math” is assigned to the variable course.
The program below demonstrated how variables work in Scala. I recommend you enter it in the Scala IDE and run it.
object VariableDemo { def main(args: Array[String]) { var score :Int = 99; val msg :String = "Data type declaration"; var score = 98; val msg2 = "With type inference"; println(score); println(msg); println(score); println(msg); } }
4. Variable Scope
Variables declared in a Scala program could have one of three different scopes. The scope of a variable depends on where they are being used. The three different scopes are explained below
fields – these are variables that belong to an object. They can be accessed from within the object and by any function defined inside the object. Fields can also be accessed from outside the containing object depending on it’s access modifier
method parameters -These are variables that are used to pass value to a method when the method is invoked. Method parameters are only accessible from inside the method
Local Variables – Local variables are variables declared inside a method. They are local to the method and only accessible inside the method.