Why val and var rock

When discussing val and var in Scala they are often seen as the alternative to Java's more long winded way of declaring variables, e.g.

Employee bob = new Employee("Bob");
vs
var bob = new Employee("Bob")
The latter is clearly more succinct and has less repetition. This is normally where the discussion ends and we declare Scala the winner.

However, Scala gives you more than this added brevity. By forcing every single variable declaration to use val or var you are forced to make a design decision.

Scala forces a conscious decision about mutability of variables

In Scala, every time you define a variable you make a decision as to whether a variable is to be immutable or not.

Java has the option of adding the final keyword to variable declarations. However, you must remember to do this every single time and it is also more effort (not much, but let's face it, we're lazy ;-)). As a result, final is omitted from many places where it could be used.

With Scala, it's far easier to remember to make things immutable.

So, why do we care about this?

Making local variables immutable can increase code quality

Immutable local variables are:

  • Easier to debug: if a variable is initialised to a value at the start of a method then it will be the same value at the end. It's one less thing you have to worry about
  • Easier to maintain: someone new to the code cannot accidentally change the value of the variable (at least not without taking the effort to change it from a val to a var)
  • Easier to test: if something can't change during a method call then you don't have as much to consider when testing

And that is why I think val and var rock :)

Discussion

blog comments powered by Disqus

Colin Howe

I'm Colin. I like coding, ultimate frisbee and startups. I am VP of engineering at Conversocial