Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
Soumya Simanta Avatar asked Oct 27 '12 04:10

Soumya Simanta


People also ask

Why is Val better than VAR in Scala?

The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable. Because val fields can't vary, some people refer to them as values rather than variables.

What is the difference between a VAR Def and Val in Scala?

There are three ways of defining things in Scala: def defines a method. val defines a fixed value (which cannot be modified) var defines a variable (which can be modified)

What does Val mean in spark?

"val means immutable and var means mutable." To paraphrase, "val means value and var means variable".

What is true about the keywords Val and VAR?

The keywords var and val both are used to assign memory to variables at the running only. The difference is in the mutability of variables that are initialized using these keywords. var keyword initializes variables that are mutable, and the val keyword initializes variables that are immutable.


1 Answers

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.
like image 137
Kim Stebel Avatar answered Nov 03 '22 02:11

Kim Stebel