Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extend an enum with additional values?

Tags:

If I have an enum with a set of values, is there a way I could create a second enum with the same variants plus some more?

// From this enum Base {     Alpha,     Beta(usize), }  // To this, but without copy & paste enum Extended {     Alpha,     Beta(usize),     Gamma, } 
like image 912
Shepmaster Avatar asked Aug 09 '14 00:08

Shepmaster


People also ask

Can we extend an enum to add elements?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

Can you extend an enum?

The short answer is no, you can't extend enums because TypeScript offers no language feature to extend them.

Can you add values to enum?

You can add a new value to a column of data type enum using ALTER MODIFY command. If you want the existing value of enum, then you need to manually write the existing enum value at the time of adding a new value to column of data type enum.

Why we Cannot extend enum?

In byte code, any enum is represented as a class that extends the abstract class java. lang. Enum and has several static members. Therefore, enum cannot extend any other class or enum : there is no multiple inheritance.


1 Answers

An enum can't be directly extended, but you use the same composition trick one would use with structs (that is, with a struct, one would have a field storing an instance of the 'parent').

enum Base {     Alpha,     Beta(usize), }  enum Extended {     Base(Base),     Gamma } 

If you wish to handle each case individually, this is then used like

match some_extended {     Base(Alpha) => ...,     Base(Beta(x)) => ...,     Gamma => ... } 

but you can also share/re-use code from the "parent"

match some_extended {     Base(base) => base.do_something(),     Gamma => ..., } 
like image 122
huon Avatar answered Sep 22 '22 14:09

huon