0
votes

As per Scala Doc,

Case classes are good for modeling immutable data.

But that functionality can be achieved by an immutable map too. I'm aware that one can fix the number of keys by specifying the parameter list in case class but apart from this, I wanted to understand in what cases case classes would be a better choice than a map?

1
All the member data elements can be of different types. - jwvh
Map is not good for modelling immutable data. - Tim
It's handy for pattern matching and type safety. As jwvh said, maps are not heterogenous. Also, it's just less verbose. When you have some fixed properties, case classes are useful. When you have a bunch of properties, maps are better. - user
@jwvh Good point. Missed it - Pritam Pathak
Another important point. You can not safely access a property of a Map. Like even if you know that your map has the key name doing map("name") is unsafe and many linters will want you, and doing map.get("name") implies you have to deal with an option that you known will be a some always. On the other hand, user.name is statically proven to be correct. - Luis Miguel Mejía Suárez

1 Answers

1
votes

As has been mentioned in the comments, I'll summarize the points here in order to close this.

Case classes are a better choice in the following cases:

  • When the parameters are having heterogeneous type
  • To ensure parameter signature remains constant and cannot be modified