scala

Case classes in Scala!

At first, when I got introduced to case classes in Scala, I thought, why then hell does Scala have another way of creating classes? My initial google search taught me that case classes are classes specifically meant for holding data with minimum ceremony.

The java way of doing this would be to (Usual way of creating model classes);

  • Define a class with bunch of private fields.
  • Write constructor with all these fields as the parameters.
  • Define getters and setters for each of the fields.
  • Make the class extend the Serializable interface.

Scala does this all underneath the hood for you if you create a case class. That is right! case class is just Java classes on steroids. Well, since we are talking about Scala, how is it different from normal classes in Scala?

The fun thing here is case classes can also be considered as Scala classes on steroids, how you might ask. Case classes, would also do the following things besides just creating a class;

  • Creates the class along with a companion object.
  • A default toString method that includes all the fields and not the annoying @ and hex strings.
Normal class would give you the hex string while the case class object would give a more meaningful toString
  • A copy method that allows to create a new copy of the object with the exact same fields.
  • equals and hashCode methods would be overridden will be dependent on the fields instead of the meaningless object reference. This helps a lot with the objects being able to be added into List and Maps.

Finally, if your case class does not require any fields but just methods, we can go ahead and just create a case object directly.

Would just create an object with all the features specified above

Seems like this is not just a thing in Scala. Kotlin, a language heavily inspired by Scala also has this construct, but they call it data classes(https://kotlinlang.org/docs/reference/data-classes.html).

So, I hope its now a bit more clear as to why the hell is there another way to create classes and objects in Scala. Use them exactly by knowing where and when to use them.

Standard

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.