Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where case classes should NOT be used in Scala?

Tags:

Case classes in Scala are standard classes enhanced with pattern-matching, equals, ... (or am I wrong?). Moreover they require no "new" keyword for their instanciation. It seems to me that they are simpler to define than regular classes (or am I again wrong?).

There are lots of web pages telling where they should be used (mostly about pattern matchin). But where should they be avoided ? Why don't we use them everywhere ?

like image 772
Alban Linard Avatar asked Jan 22 '10 18:01

Alban Linard


People also ask

For which kind of data should you use a case class in Scala?

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.

Why do we use case class in Scala?

The one of the topmost benefit of Case Class is that Scala Compiler affix a method with the name of the class having identical number of parameters as defined in the class definition, because of that you can create objects of the Case Class even in the absence of the keyword new.

Can we use CASE classes in pattern matching?

Case classes help us use the power of inheritance to perform pattern matching. The case classes extend a common abstract class. The match expression then evaluates a reference of the abstract class against each pattern expressed by each case class.

What is the difference between Case class and class in Scala?

A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).


1 Answers

There are many places where case classes are not adequate:

  • When one wishes to hide the data structure.
  • As part of a type hierarchy of more than two or three levels.
  • When the constructor requires special considerations.
  • When the extractor requires special considerations.
  • When equality and hash code requires special considerations.

Sometimes these requirements show up late in the design, and requires one to convert a case class into a normal class. Since the benefits of a case class really aren't all that great -- aside from the few special cases they were specially made for -- my own recommendation is not to make anything a case class unless there's a clear use for it.

Or, in other words, do not overdesign.

like image 51
Daniel C. Sobral Avatar answered Sep 20 '22 17:09

Daniel C. Sobral