11
votes

case classes have some nice percs, like copy, hashCode, toString, Pattern Matching. Why not make every Scala class a case class?

2
One of the main reasons is that you cannot have case class to case class inheritance.Ende Neu
@Make42 -- sorry, my answer was mistaken. I have removed it. Will write a new one.Sachin Tyagi

2 Answers

9
votes

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 an equals method on an object holding a database connection? Would it make sense for it to be Serializable? 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 another case class, which may go against how you are modeling your domain. Why? Short answer: equality. You can find a longer answer here.

3
votes

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