How to extend existing enumeration objects in Scala?

I am wondering if you can extend existing listings in Scala. For instance:

object BasicAnimal extends Enumeration{ type BasicAnimal = Value val Cat, Dog = Value } 

Can this be expanded as follows:

 object FourLeggedAnimal extends BasicAnimal{ type FourLeggedAnimal = Value val Dragon = Value } 

Then the elements in FourLeggedAnimal will be Cat, Dog and Dragon. It can be done?

+6
source share
2 answers

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

+3
source

Maybe so:

 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 note: it is not possible to use E1 values ​​from E2 by name:

 E2.A // Can not resolve symbol A 

But you can name them like this:

 E2(0) // A 

or

 E2.withName(E1.A.toString) // A 
+1
source

Source: https://habr.com/ru/post/892832/


All Articles