Variables can be defined as the reserve space in memory to store the assigned values. Based on the Datatype of the variable the memory is allocated by the compiler/type system and the value pertaining to that variable is stored.
Scala Variable Declaration
Variable declaration specifies the name of the variable that would be stored in the memory which can be accessed further with this name. The syntax for declaring variable is;
1 2 3 |
var variablename : datatype = value |
var is a keyword indicating it is a variable followed by the variable name and datatype, value indicates the initial variable value.
For Example;
1 2 3 |
var studentId:Int = 12 |
The keyword var indicates that studentId is a variable and is of type Int. The value of the studentId is initialised to 12 and this value can be changed by the programmer.
Constants can also be declared using the following syntax;
1 2 3 |
val variablename:datatype = value |
val is the keyword followed by the variable name and data type. value on the right hand side indicates the value that remains unchanged meaning we cannot change the value in the program.
For Example;
1 2 3 |
val pi= 3.14f |
pi is the name of the variable with the keyword val and the value initialized to 3.14. val indicates that the value of pi variable cannot be changed.
Try changing it as below;
1 2 3 4 5 6 7 |
scala> pi=5 <console>:8: error: reassignment to val pi=5 ^ scala> |
Variable Data Types
The variable data type is specified after the variable name and before the equal sign. “Datatype” indicates the type of the variable i.e. is whether it is integer, string etc.
The syntax for declaring variable with datatype is
1 2 3 4 5 |
var variablename:Datatype = value OR val variablename:Datatype = value |
For example;
1 2 3 4 |
var studage:Int = 8 val studid:Int = 4 |
The above declared variables studage and studid indicates these variables are of type Integer.
Variable Type Inference
The phenomenon in which the Scala compiler can identify the type of the variable based upon the initial value assigned is called Variable Type Inference. This is carried out by the typesystem interface.
The variable can be declared as;
1 2 3 4 |
val studid = 10; var studname = "Adam" |
Here we are not specifying the data type but depending on the value assigned, the compiler identifies the data type of the variable studid as integer and studname as string.
Multiple Assignments
A block of code can return a tuple and can be assigned to a variable. Multiple assignments of variables are supported in Scala.
For Example variables can be declared as;
1 2 3 |
val(sid:Int,sname:String) = (12,"John") |
The above example declares two variables sid of Integer type and sname of String type with the values assigned to it enclosing the round brackets.
OR
1 2 3 |
val(sid,sname)=(12,"John") |
Here we are not specifying the data type instead assigning the initial values.
Now let us understand the above concepts with an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Student { var sid:Int = 10 var sname = "John" var marks = 72.5f val(sage,city) = (13,"Mysore") def studdetails() { println("Student Id is:"+sid); println("Student Name is:"+sname); println("Marks secured is:"+marks); println("Student Age is:"+sage); println("City is:"+city); } } |
Here we create a student class with variables sid, sname, marks, city and sage variables. sage and city are multiple assignment and the method studdetails display all the student details when this method is called.
1 2 3 4 5 6 7 8 |
object test { def main(args:Array[String]) { val st = new Student(); st.studdetails() } } |
Create object test and create the student object and invoke the studdetails method. Note that a tuple is a pair of values and we will discuss this in detail later.
Now run the above code by typing test.main(null)
Output:
1 2 3 4 5 6 7 |
Student Id is:10 Student Name is:John Marks secured is:72.5 Student Age is:13 City is:Mysore |
Below image shows the above programs in execution in Scala shell.
Variable Scope/Types
Scala variables are categorized into three scopes depending on the place where they get declared. They are fields, method parameters and local variables. Let us discuss these one by one.
Field variables: These type of variables are accessible from every method in the object and from outside the object depending on the type of access modifiers used to declare the field. They belong to an object and can be mutable or immutable depending upon the var and val keywords.
Consider an example to depict the field variables;
1 2 3 4 5 6 7 8 9 10 |
class Window { var height = 3.2f var width = 5.6f def windet() { println("Window height is :"+height) } println("Window width is :"+width); } |
Window class is created with field variables height and width. These two variables can be accessed inside a method and invoked this from an object by creating reference.
Create object Win as shown below;
1 2 3 4 5 6 7 8 |
object Win { def main(args:Array[String]) { val win = new Window() win.windet() } } |
We create a window object “win” and and access the variables height and width.
Run the above code by executing Win.main(null)
Output:
1 2 3 4 |
Window width is :5.6 Window height is :3.2 |
Method Parameters: These are the variables used to pass a value inside the method whenever the method is called. These variables can be accessed inside the method and outside the method if there is a reference to the object from outside the method. These variables are always mutable defined with val keyword.
Consider an example for method parameters;
1 2 3 4 5 6 7 8 |
class Subtract { def sub(s1:Int,s2:Int){ var res = s1-s2 println("Result is:"+res); } } |
Subtract class is created with sub method accepting two method parameter variables s1 and s2.
1 2 3 4 5 6 7 8 |
object TestSub { def main(args:Array[String]){ val su = new Subtract() su.sub(40,10) } } |
TestSub object is created and sub method is invoking by passing the values to variables s1 and s2.
Run the code by typing TestSub.main(null)
Output:
1 2 3 |
Result is:30 |
Local Variables: Local variables are the variables declared inside a method.These are accessible inside a method only. These can be both mutable and immutable depending on var and val keywords.
Consider an example for method parameters;
1 2 3 4 5 6 7 8 9 |
class Addition { def add() { var(a,b) = (10,20); var c = a+b; println("Result is:"+c) } } |
Here we create a class Addition and define a method with variables a, b and c inside a method. If we try to access the variable a, b and c outside the method an error is thrown not found value a.
Create object Test to access the method variables as;
1 2 3 4 5 6 7 8 |
object Test { def main(args:Array[String]) { val ad = new Addition() ad.add() } } |
Run the code by executing the command Test.main(null)
Output:
1 2 3 |
Result is:30 |
That’s all for variables in Scala Programming language and their scopes, we will look into more core features of Scala in coming posts.