Reputation: 11741
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
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
Reputation: 42047
Here are some reasons for vars in Scala:
Upvotes: 22