Soumya Simanta
Soumya Simanta

Reputation: 11741

When is it okay to use "var" in Scala?

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?

Upvotes: 18

Views: 6946

Answers (2)

paradigmatic
paradigmatic

Reputation: 40461

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.

Upvotes: 11

Kim Stebel
Kim Stebel

Reputation: 42047

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.

Upvotes: 22

Related Questions