Consider the following code:
case class Vector3(var x: Float, var y: Float, var z: Float)
{
def add(v: Vector3): Unit =
{
this.x += v.x
this.y += v.y
this.z += v.z
}
}
As you can see, the case class
holds mutable state. It is highly discouraged to do this and normally I'd agree and absolutely stick to this "rule", but here goes the whole story.
I'm using Scala to write a little 3d-game-engine from scratch. So first I thought about using a (much more) functional style, but then the garbage-collector would kick in too often.
Think about it for a moment: I have dozens and dozens of entities in a test-game. All of them have a position (Vector3), an orientation (Vector3), a scale (Vector3) and a whole lot of Matrices too. If I was about to go functional in these classes (Vector3 and Matrix4) and make them immutable I would return hundreds of new objects each frame, resulting in a huge fps-loss because, let's face it, GC has its uses, but in a game-engine and with OpenGL... not so much.
Vector3 was a class before, but it is a case class now, because somewhere in the code I need pattern-matching for it.
So, is it really that bad to use a case-class that holds mutable state?
Please do not turn this into a discussion about "Why do you even use Scala for a project such as that?" I know that there may be better alternatives out there, but I'm not interested in writing (yet another) engine in C++, nor am I too eager to dive into Rust (yet).