While working on one of my Scala project, I came across a requirement to create enum values having
name and description. I tried to find a solution in Scala for this, while
searching this I came across a question, Can I have a Scala enum unlike Java?. Answer to this is both
Yes and No.
-
No
Because there is no direct approach to create an enum value in Scala having any value other then name. -
Yes
Because we can achieve this by extending Scala enumeration functionality. Another approach could be a Case Objects as Scala pattern matching is quite strong.
Extending Scala Enumeration
This approach allows us to extend Scala Enumeration functionality, by extending Val class.Advantages
- Enumerations will generally be a bit less code to write.
- Enumerations are a bit easier to understand for someone new to Scala since they are prevalent in other languages.
Extending Scala Enumeration
Case Objects
This approach allows us to create Enumeration using Case Objects.Advantages
- When using sealed case classes/Case Objects, the Scala compiler can tell if the match is fully specified.
- Case classes naturally supports more fields than a Value based Enumeration, which supports a name and Id.
Case Objects
Post a Comment
Post a Comment