When to use mutable vs immutable classes in Scala
Much is written about the advantages of immutable state, but are there
common cases in Scala where it makes sense to prefer mutable classes?
(This is a Scala newbie question from someone with a background in
"classic" OOP design using mutable classes.)
For something trivial like a 3-dimensional Point class, I get the
advantages of immutability. But what about something like a Motor class,
which exposes a variety of control variables and/or sensor readings? Would
a seasoned Scala developer typically write such a class to be immutable?
In that case, would 'speed' be represented internally as a 'val' instead
of a 'var', and the 'setSpeed' method return a new instance of the class?
Similarly, would every new reading from a sensor describing the motor's
internal state cause a new instance of Motor to be instantiated?
The "old way" of doing OOP in Java or C# using classes to encapsulate
mutable state seems to fit the Motor example very well. So I'm curious to
know if once you gain experience using the immutable-state paradigm, you
would even design a class like Motor to be immutable.
No comments:
Post a Comment