Scala Variables

Variable is a name of reversed memory area of any values. In scala we can declare a variable with var and val keywords.

Declare variable with var :

Variable declare with var can change value.This type variable called mutable.
var varName : datatype = Initial value
ex: var age : int = 10
or we also use below syntax to declare variable
var age =10
In this case we can change the value of age.
defmain(args: Array[String]) {
varage: Int =10;
varname= “scala”;
println(” age=”+age+“name =”+name);
//now we will change the values ogage and name
println(“after changing the values of age and name”);
println(“age=”+age+“name =”+name);
age=10 name =scala
after changing the values of age and name
age=30 name =java

Declare variable with val:

Variable declare with val can not their value.This type variable called immutable.
val variableName : datatype = Initial value
val varaibleName = Initial value
defmain(args: Array[String]) {
valage: Int =10;
// age = age+10 // we can not change value of valtype varaibles
we can not change of value of val type variable. They behavior  like constant.

Multiple assignments:

Scala support to multiple assignments. We can assign multiple variable in a tupple.
val (var1: Int, var2: String) = Pair(10, “scala”)
And the type inferencer gets it right:
val (var1, var2) = Pair(10, “java”)
defmain(args: Array[String]) {
val(val1: Int, val2: String) = Pair(10, “scala”);
println(” val1 =”+val1+” val2 =”+val2);
val1 =10 val2 =scala

Variable Type:

variables in scala are three type fields , method parameter and local variables.


Fields are variables that belong to an object. The fields are accessible from inside every method in the object. Fields can also be accessible outside the object, depending on what access modifiers the field is declared with. Fields can be both val’s and var’s.

Method parameters:

Method parameters are variables which values are passed to a method when the method is called. Method parameters are only accessible from inside the method – but the objects passed in may be accessible from the outside, if you have a reference to the object from outside the method. Method parameters are always val’s.we can say method parameter is immutable.

Local variables:

local variables are variables declared inside a method. Local variables are only accessible from inside the method, but the objects you create may escape the method if you return them from the method. Local variables can be both var’s and val’s


Leave a Reply

Your email address will not be published. Required fields are marked *

69 − 61 =