case classes have some nice percs, like copy, hashCode, toString, Pattern Matching. Why not make every Scala class a case class?
A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.
The answer is simple: Case Class can extend another Class, trait or Abstract Class. Create an abstract class which encapsulates the common behavior used by all the classes inheriting the abstract class.
A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).
The Scala interface for Spark SQL supports automatically converting an RDD containing case classes to a DataFrame. The case class defines the schema of the table. The names of the arguments to the case class are read using reflection and they become the names of the columns.
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.
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).
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