Vals and vars
While writing our Scala programs, we can define our member fields using either val
or var
keywords. When we use a val
keyword to assign a value to any attribute, it becomes a value. We're not allowed to change that value in the course of our program. So a val
declaration is used to allow only immutable data binding to an attribute. Let's take an example:
scala> val a = 10 a: Int = 10
Here, we have used a val
keyword with an attribute named a
, and assigned it a value 10
. Furthermore, if we try to change that value, the Scala compiler will give an error saying: reassignment to val
:
scala> a = 12 <console>:12: error: reassignment to val a = 12
Scala recommends use of val
as much as possible to support immutability. But if an attribute's value is going to change in the course of our program, we can use the var
declaration:
scala> var b = 10 b: Int = 10
When we define an attribute using a var
keyword, we're allowed to change its value. The var
 keyword here stands for...