I have normal Scala class I am wanting to refactor to become an immutable case class. As I'm needing the class to be well-behaved in Set
operations, I want all the Scala compiler automatically generated methods provided on a case class. IOW, I am wanting to avoid having to write these various methods; equals
, hashCode
, toString
, etc., as that is very error prone. And I am needing to do this for a raft of classes, so I need a general solution, not just a specific solution anomalous quick fix or hack.
Here's the class with which I am working:
class Node(val identity: String, childrenArg: List[Node], customNodeArg: CustomNode) {
val children: List[Node] = childrenArg
val customNode: CustomNode = customNodeArg
}
As you can see, the class's constructor has three parameters. The first one, identity
, is a read-only property. The remaining two, childrenArg
and customNodeArg
, are just a normal method parameters; i.e. they are only present during the construction of the instance and then disappears altogether from the class instance (unless otherwise captured) upon execution completion of the class constructor.
My first naive attempt to convert this to an immutable case class was this (just removing val
from the first parameter):
class Node(identity: String, childrenArg: List[Node], customNodeArg: CustomNode) {
val children: List[Node] = childrenArg
val customNode: CustomNode = customNodeArg
}
However, this resulted in the undesired effect of both the childrenArg
and customNodeArg
parameters now being elevated to become (read-only) properties (as opposed to leaving them as normal method parameters). And this had the further undesired effect of having them included in the compiler generated equals
and hashCode
implementations.
How do I mark the immutable case class's constructor parameters childrenArg
and customNodeArg
such that identity
is the only read-only property of the case class?
Any guidance on this; answers, website discussion links, etc., are greatly appreciated.