I'm wondering if you can extend already existing enumerations in Scala. For example:
object BasicAnimal extends Enumeration{
type BasicAnimal = Value
val Cat, Dog = Value
}
Can this be extended something like this:
object FourLeggedAnimal extends BasicAnimal{
type FourLeggedAnimal = Value
val Dragon = Value
}
Then, the elements in FourLeggedAnimal would be Cat, Dog and Dragon. Can this be done?
The in-built method to create enumerations in Scala is done by extending with the abstract class Enumeration. However, there are some major issues with this approach, such as: 2.2. Using Algebraic Data Type (ADT) Due to the issues with Scala’s Enumeration, enums are often created as ADTs using sealed traits and case objects.
Scala provides an Enumeration class which we can extend in order to create our enumerations. Every Enumeration constant represents an object of type Enumeration. Enumeration values are defined as val members of the evaluation. When we extended the Enumeration class, a lot of functions get inherited. ID is one among the them.
To extend a class in Scala we use extends keyword. there are two restrictions to extend a class in Scala : To override method in scala override keyword is required. Only the primary constructor can pass parameters to the base constructor. class base_class_name extends derived_class_name { // Methods and fields }
Because it uses a “case object” approach it generates about four times as much code as an Enumeration, but depending on your needs it can also be a good approach: If you found this tutorial helpful, you can find over 250 more examples in my book, the Scala Cookbook:
No, you cannot do this. The identifier BasicAnimal
after extends
is not a type, it is a value, so it won't work, unfortunately.
May be that's the way:
object E1 extends Enumeration {
type E1 = Value
val A, B, C = Value
}
class ExtEnum(srcEnum: Enumeration) extends Enumeration {
srcEnum.values.foreach(v => Value(v.id, v.toString))
}
object E2 extends ExtEnum(E1) {
type E2 = Value
val D, E = Value
}
println(E2.values) // prints > E2.ValueSet(A, B, C, D, E)
One remark: it's not possible to use E1 values from E2 by name:
E2.A // Can not resolve symbol A
But you can call them like:
E2(0) // A
or:
E2.withName(E1.A.toString) // A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With