Is there a way to ensure that you switch all specific enum values ​​in Java?

Suppose you have an enumeration with three values:

enum Colors { RED, GREEN, BLUE }

You switch all the values ​​in a method, thinking that you have handled all the cases:

switch (colors) {
    case RED: ...
    case GREEN: ...
    case BLUE: ...
}

Then you add the new value to the enumeration:

enum Colors { RED, GREEN, BLUE, YELLOW }

And everything still compiles fine, except that you silently skip the case for YELLOWin method. Is there a way to raise a compile-time error in such a scenario?


: , Java. "", , , , , / ,

+6
3

. Eclipse IDE .

Windows/Preferences / Java "" "switch on cases" enum " " ".

EDIT:

, " ".

+6

. - . , :

enum Color { 
    RED {
        @Override
        public void foo() { ... }
    },
    GREEN {
        @Override
        public void foo() { ... }
    },
    BLUE {
        @Override
        public void foo() { ... }
    };

    public abstract void foo();
}

, , , .

switch (color) {
    case RED: ...
    case GREEN: ...
    case BLUE: ...
}

color.foo();

, Kotlin , , Kotlin .

, BLUE - , . "", "".

+8

, . .

switch . , , , , .

+1

All Articles