I'm defining a Scala class today, and I think "I need an equals
method and a hashCode
method; and a copy
method would be handy too. I'll turn this into a case class." My class already has a bunch of other code, and is in no way trivial.
So fine, it all works and everything, but when the text books deal with case classes, all of the examples define them for use as value classes or 'data transfer objects'. Is it appropriate to define a non-trivial case class? Is the thought process described above OK, or do I need to think of case classes differently?
A case class
provides, equals
, hashCode
and toString
methods based on the main constructor parameters, all of which are turned into val
too. In addition, the object companion gets an apply
and an unapply
methods, again based on the main constructor parameters.
Also, a case class
inherits from Serializable
and from Product
, and should not be extended by other classes.
If all of these things are appropriate for your class, then feel free to declare it as a `case class'.
Feel free, provided it doesn't have descendants. Extending case classes is a bad idea.
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