Difference between Scala val and var

By February 23, 2011 at 7:45 pm · Scala

In Scala Language you can define a variable using either a val or a var keyword. The variables defined using val keyword are immutable and can’t be changed after initialization. And the variable defined using var keyword are mutable and can be changed any number of times until it is present in the scope.

The immutability applies to the variable and not the instance to which the variable refers. For example, if we write
 val buffer = new StringBuffer()
we can’t change what buffer refers to. However, we can modify the instance of StringBuffer using methods like append( ).
On the other hand, if we define an instance of String using
 val str = "Vigilance" 
we can’t modify the instance as well because String itself is immutable. You can make an instance of a class immutable by defining all of its fields using val and providing only the methods that let you read, and not modify, the state of the instance.
In Scala, you should prefer using val over var as much as possible since that promotes immutability and functional style.

DeeKay has been working in Java, JEE and opensource technology since 7 years and has same years of experience in software development. His area of interest is TDD, Scala langauge, Java, JEE techologies.

Related Posts

Popular Posts