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.

- 1
- 1

- 11,253
- 4
- 35
- 63
-
"entity objects" often means something nearly opposite: a class for which identity is important, and so it can't be a case class. – Alexey Romanov Oct 04 '16 at 18:02
-
Maybe I'm wrong but I'm not sure the identity of an entity object should be tied on the object sharing the same address on the machine but rather from an intrinsic identity value. If two values are the same they are even on networked computers. – stefanobaghino Oct 04 '16 at 18:20
-
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).

- 3,381
- 2
- 21
- 31
-
-
"Case classes have clear semantics" - are reason to use them, not not to use them ;-). – Make42 Oct 04 '16 at 13:17
-
1I didn't want to describe in details what is "idiomatic scala style", because that can cause an irrelevant to question holywar. Briefly -- avoid mutable state, avoid side effects, describe actions as combinations of functions. About second question -- sometimes you cannot guarantee that semantics, or even you are going to break it. For example, std library builders have a state => cannot be case classes, `RedBlackTree`'s `copy` would have to take care about tree's integrity, and that's out of `copy`'s scope of responsibility. – dveim Oct 04 '16 at 13:30
-
@Make42: "Case classes have clear semantics" - are reason to use them, **iff** the class in question has case class semantics! – Jörg W Mittag Oct 04 '16 at 13:31