12

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?

Henry
  • 175
  • 1
  • 5

2 Answers2

4

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

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
  • Oh, I see the error of my ways. I've added a new response, so I can write the code properly. – Henry Jul 15 '11 at 13:50
  • 1
    It won't let me post because of reputation. Basically, you can define the objects as abstract classes and extend them, then instantiate objects that directly extend the corresponding classes. – Henry Jul 15 '11 at 13:51
2

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
far.be
  • 689
  • 6
  • 8
  • I like this idea, total is for Enum that are static types, it does not matter that you end up repeating them, the only complicated thing would be if you need to use the ID to save in database, you should define ranges to avoid creating confusion ... – Rodo Mar 04 '18 at 20:36