18

I know that Scala has var (for mutable state) but pure functional programming discourages use of any mutable state and rather focuses on using val for everything.

Coming from an imperative world it's hard to let go of mutable state.

My question is when is it okay to use var in your Scala code ? Can all code really be done using just val. If yes, then why does Scala have vars?

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
Soumya Simanta
  • 11,523
  • 24
  • 106
  • 161

2 Answers2

21

Here are some reasons for vars in Scala:

  • Scala is a multi-paradigm language, it encourages functional programming, but it leaves the choice to the programmer.
  • Comptibility: Many Java APIs expose mutable variables.
  • Performance: Sometimes using a var gives you the best possible performance.
  • When people say that everything can be done without vars, that is correct in the sense that Scala would still be turing complete without vars. However, it doesn't change anything about the validity of the previous points.
Kim Stebel
  • 41,826
  • 12
  • 125
  • 142
  • Thanks for the awesome answer. But could you please provide us some reference for `Scala would still be turing complete without vars.` – Vishrant Jul 12 '18 at 14:16
  • I just ran into an instance where var made sense: I had to write a common function that adds up some integers into a bit-mask. I created a function that made a var accumulator and then on certain conditions added values to that var, and then returned the final result. The var is not exposed to any other code, encapsulated in a single function. This can be rewritten to use a val, however, for each case that needed addition to the original var, you'd have to create a new val to add to it for the return statement. Using val here would increase memory overhead usage for the sake of immutability... – Rimer Mar 25 '20 at 15:28
10

Even from a functional programming point of view, you can use vars (or mutable objects) locally, if they don't leave the scope where they are defined.

For instance, consider this (contrived) function, which returns the size of a list:

def dumbSize( lst: List[Int] ): Int = {
   var i = 0
   var rest = lst
   while( rest != Nil ) {
     i += 1
     rest = rest.tail
   }
   i
}

Although this (ugly) function uses vars, it is still pure. There are no side effects and it will always return the same result for a given argument value.

Another example of "mutable-state-encapsulation" is the actor model, where actor state is often mutable.

blackraven
  • 5,284
  • 7
  • 19
  • 45
paradigmatic
  • 40,153
  • 18
  • 88
  • 147