Search code examples
scalafunctional-programmingvarmutable

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?


Solution

  • 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.