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?
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.
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)
"val means immutable and var means mutable." To paraphrase, "val means value and var means variable".
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.
Here are some reasons for vars in Scala:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With