Scala – When to use case class or regular class

scala

I have some misunderstanding in what cases I should use case class or regular class following by best practices. I have already read about differences of both classes but cannot imagine myself real-life examples where is reccommended to use case or regular class.

Could anybody show me real examples with explanation why it's reccommended to do so and not otherwise?

Best Answer

If you are going to write purely functional code with immutable objects, you should better try avoid using regular classes. The main idea of the functional paradigm is the separation of data structures and operations on them. Case Classes are a representation of a data structure with the necessary methods. Functions on the data should be described in different software entities (e.g., traits, objects).

Regular classes, on the contrary, link data and operations to provide the mutability. This approach is closer to the object-oriented paradigm.


As a result, do not use Case Classes if:

  1. Your class carries mutable state.
  2. Your class includes some logic.
  3. Your class is not a data representation and you do not require structural equality.

However, in these cases, you should really think about the style of your code because it probably is not functional enough.

Related Topic