Let's say I have an enum Color containing the possible color-values for my program: red, blue and orange. And then I would like to add methods that work on those colors. How can I add those methods in Scala?
enum Color {
case Red
case Blue
case Orange
}
I'm using Scala version 3.
I tried making a class that takes as parameter a value of the enum type Color, and contains the methods needed for the enum. I do however think that there is a better way to handle this case.
CodePudding user response:
You can add methods directly to the enum.
enum Color {
case Red
case Blue
case Orange
def colorToInt: Int = this match {
case Red => ...
case Blue => ...
case Green => ...
}
// etc ...
}
Alternatively, each enum case can be given its own methods. Depending on how many enum cases you have, it can be neater to write code in this style.
enum Color {
case Red extends Color {
override def colorToInt: Int = ...
}
case Blue extends Color {
override def colorToInt: Int = ...
}
case Orange extends Color {
override def colorToInt: Int = ...
}
def colorToInt: Int // Note: abstract method
}
Enums and their cases are effectively syntax sugar for features that have already existed in Scala 2, such as case classes and sealed abstract classes. So conceptually, you can think of enum
as defining a full-fledged abstract class and each case
as defining a subclass. They can all have methods, the cases inherit methods from the enum, and the whole thing works like an OOP class hierarchy, because it actually is one.
You can read about the exact translations that take place on the original issue tracker for the feature. Effectively, every case
gets compiled to either a case class
or a val
, depending on whether any custom methods are needed on it.