Scala Enumeration for 2.x

Time to assemble everything we learned in the recent episodes !

We are going to use sealed, pattern matching, trait, case object, map, etc…

What you are about to see here is good knowledge to keep but the exact use case and application showed here will be deprecated in Scala 3. However, the underlying features and logic we are using will still be here so it is not a loss !

We are writing an Ore management software today.

Notice how we are able to describe the Ores with a finite number of possibilities. If we want a new one, we need to add it ourselves. Did you notice the warning about pattern matching :

warning: match may not be exhaustive.
Since we are using sealed, the compiler can know exactly the number of options available for this type. So the compiler can help us !

We could simply have a ore: String of course. But noticed the typo in Godl instead of Gold ? And the compiler caught it for us !

The rest of the exercise is just to go a bit further and play with what we built.

You can set up a system for reporting, and add handy calculation with lazy val.

You can also set up special case like for Iron in the last example.

Something that needs to be said is that in Scala 3 this pattern will be completely changed. Scala 3 will implement its shortcut version for Enumeration that will pretty much write this boiler plate code for us. But all those features to customize it yourself will still be available so it is not a loss to know about it !

I hope this little exercise with a more applicable example was fun! If you have any feedback, as always, don’t hesitate to comment below or message me on the Discord server. Looking forward to hearing from you.

Reveal more information and clues
Load Exercise