Scala has two types of variables, immutable and mutable. You declare immutable variables using val
and mutable variables using var
. Irrespective of the type, you must initialize the variable as you declare.
In this article, we will learn how to declare variables.
My set up details:
- I am using Scala Eclipse IDE, 4.0.0.
- JavaSE-1.8
To run the examples. Select the statements and run in scala interpreter or right click on the file and then Run-as->Scala Application.
Declare Immutable Variables
Let’s define an object and introduce an immutable int variable a. Since it is immutable we declare it using val
keyword.
ValExample.scala:
object ImmutableVariableExample { //declare an immutable variable val a = 2 print(a) def main(args: Array[String]): Unit = { } }
Output:
2
Let’s re-assign variable a
to 3. This should fail.
object ImmutableVariableExample { //declare an immutable variable val a = 2 print(a) //uncomment below code and it fail as val is immutable a = 3 def main(args: Array[String]): Unit = { } } }
Try running it and the scala interpreter will throw error as val is immutable and can’t be re-assigned.
:12: error: reassignment to val a = 3 ^
Declare Mutable Variables
Declare mutable variable with var
. The above example can be re-written using var
and you will be able to re-assign the variable.
VarExample.scala:
object MutableVariableExample { //declare a mutable variable var a = 2 println(a) println("Now re-assign it to 3") a = 3 println(a) def main(args: Array[String]): Unit = { } }
Output:
2 Now re-assign it to 3 3
Type Inference
In our above examples, we didn’t specify the variable types in the declarations. The examples still worked because of Scala’s ability to infer the types based on the initialized data.
You can however specify a type explicitly if you want.
For example,
VarExample:
object MutableVariableExample { //declare a mutable variable var a = 2 println(a) println("Now re-assign it to 3") a = 3 println(a) var b:Int = 3 var c:String = "Hi"; println(b + c) def main(args: Array[String]): Unit = { } }
Output:
2 Now re-assign it to 3 3 3Hi
Declaring nested variables with same name
In this example, I will declare the same variable again in a nested block. In java, it will throw an error but it is OK to do in Scala.
NestedVarExample.scala:
object NestedVarExample { //declare a mutable variable var a = "a" println(a) if (a == "a") { println("declare var a again") var a = "aa" println(a) } var b = "b" println(b) if (b == "b") { println("declare val b again") var b = "bb" println(b) } def main(args: Array[String]): Unit = { } }
One more thing, if you notice, I used ‘==’ to compare strings. In Scala, its perfectly fine to compare two Strings with the == operator. Of course in Java, we compare two Strings with the equals method.
Output:
a declare var a again aa b declare val b again bb
Download source code
This as an example of declaring variables in Scala. You can download the source code here: variablesExample.zip