Difference between Scala val and var

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 is 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 = "Kodehelp"

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.

References :