Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it appropriate to define a non-trivial Scala case class?

Tags:

scala

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?

like image 945
David Avatar asked Jan 08 '11 19:01

David


2 Answers

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'.

like image 149
Daniel C. Sobral Avatar answered Oct 20 '22 01:10

Daniel C. Sobral


Feel free, provided it doesn't have descendants. Extending case classes is a bad idea.

like image 44
Alexey Romanov Avatar answered Oct 20 '22 00:10

Alexey Romanov