javascriptgoogle-closure-compilergoogle-closure

Is there any way to have inheritance between Enums?


I would like to have inheritance between some of the enums I define.

Let's say I have the following code:


/**
 * @enum {!number}
 */
var MyBaseEnum = {
    IS_VALID         : 0b00000001,
    UNDER_VALIDATION : 0b00000010,
    SUBMITTING       : 0b00000100
};

/**
 * @enum {!number}
 * @extends {MyBaseEnum}
 */
var MyChildEnum = {
    AN_ODDBALL_STATE      : 0b00001000,
    ANOTHER_ODDBALL_STATE : 0b00010000
};

goog.inherits(MyChildEnum, MyBaseEnum);

/**
 * @param  {!MyBaseEnum} myEnum
 * @return {!string}
 */
function iExpectBaseEnum (myEnum) {
    switch (myEnum) {
        case MyBaseEnum.IS_VALID:
            return "It's valid, man!";
        case MyBaseEnum.UNDER_VALIDATION:
            return "Chill, I'm working on it.";
        case MyBaseEnum.SUBMITTING:
            return "Under submission, bro.";
        default:
            return 'WAT';
    }
};

/**
 * @param  {!MyChildEnum} myEnum
 * @return {!string}
 */
function iExpectChildEnum (myEnum) {
    switch (myEnum) {
        case MyChildEnum.AN_ODDBALL_STATE:
            return 'Dunno.';
        case MyChildEnum.ANOTHER_ODDBALL_STATE:
            return 'Dunno, bro.';
        // Accessing parent's IS_VALID would be nice through MyChildEnum.
        case MyChildEnum.IS_VALID:
            return "It's valid, man!";
        // But also would be nice to have it work with paren'ts value.
        case MyBaseEnum.UNDER_VALIDATION:
            return "Chill, I'm working on it.";
        case MyBaseEnum.SUBMITTING:
            return "Under submission, bro.";
        default:
            return 'WAT';
    }
};

At the moment I just can't find a way to have inheritance between my enumerations AND still have them behave like enumerations (I could do an awful ugly stinky hack of implementing my own enum system with generics, but... yuck... + I would lose a lot of juice from the compiler.

Is there any way to have inheritance between my enums or somehow solve the conceptual problem of enumeration specificity and extension?


Solution

  • I assume, that using Google Closure Compiler we can't have inheritance between enums.

    The basis of my assumption is, that Java doesn't allow an enum inherit another one (though there is room for some nastiness using interfaces), and Google Closure Compiler seems to be heavily inspired by Java.