case classes have some nice percs, like copy, hashCode, toString, Pattern Matching. Why not make every Scala class a case class?
2 Answers
A case class
is extremely good to hold complex values, like entity objects. They are thought precisely for that case, so they provide you methods that make sense precisely for this use case by synthesizing the methods you mentioned and furthermore making your class Serializable
and creating a companion object with a "factory" method (other than the extractor for pattern matching).
The drawbacks are the following:
some of the properties that a
case class
has may not be interesting for the class you're creating: would you want anequals
method on an object holding a database connection? Would it make sense for it to beSerializable
? And if it did, would it be secure?all these features are not free: they require the compiler to do some extra work and add to your final artifact size; why having these if you don't need the extra features a
case class
provides?you cannot inherit from
case class
to anothercase class
, which may go against how you are modeling your domain. Why? Short answer: equality. You can find a longer answer here.
Case classes have clear semantics -- data container
(much better POJOs or ADT blocks, depends on your background).
Sometimes methods like copy
or unapply
can have confusing meaning -- e.g. if fields are mutable. Case classes are designed to be used in "idiomatic scala style", that might not be applicable everywhere.
Last but not the least -- technical disadvantages (more code in .class, more code to serialize, issues with inheritance).