[Scala] `class` and `case class`

1 minute read

In Scala, there are two types of classes: normal classes and case classes. Here are the main differences between them:

  • Boilerplate code: Case classes generate a lot of boilerplate code automatically, such as equals, hashCode, toString, and a copy method. Normal classes don't have this automatic generation of code, so you have to write it yourself.

  • Immutability: By default, case classes are immutable, meaning that their fields cannot be changed after they are created. Normal classes, on the other hand, can be either mutable or immutable, depending on how you define them.

  • Pattern matching: Case classes are designed to work well with pattern matching, because they have a built-in unapply method that allows you to extract their fields. Normal classes don't have this method, so you need to define your own extractor object or method if you want to use them in pattern matching.

  • Default arguments: Case classes allow you to define default values for their constructor arguments, making it easier to create instances of the class. Normal classes don't have this feature.

  • Inheritance: Case classes can inherit from other classes or traits, but they are not recommended for use in complex inheritance hierarchies. Normal classes are more flexible in this regard.

Overall

case classes are a convenient way to define simple data structures that are immutable and can be easily used with pattern matching. If you need more flexibility or functionality, such as mutable state or complex inheritance, you should use a normal class instead.