Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend existing enumerations objects in Scala?

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?

like image 550
Henry Avatar asked Jul 15 '11 13:07

Henry


People also ask

How to create enums in Scala?

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.

What is ID in Scala enumeration?

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.

How to extend a class in Scala?

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 }

Why should I use case over enumeration in Scala?

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:


2 Answers

No, you cannot do this. The identifier BasicAnimal after extends is not a type, it is a value, so it won't work, unfortunately.

like image 181
Jean-Philippe Pellet Avatar answered Sep 22 '22 05:09

Jean-Philippe Pellet


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
like image 35
far.be Avatar answered Sep 22 '22 05:09

far.be