Boris Strandjev
Boris Strandjev

Reputation: 46963

Weird compilation error when using switch on enumeration

I just noticed one curious case and wanted to see if someone will be able to explain it. Here is my case:

private enum Classifiers {
    NEURAL_NETWORK, NEAREST_NEIGHBOURS, IDENTITY;
}
private ClassifierInterface getClassifierInstance(Classifiers classifier) {
    switch (classifier) {
    case NEURAL_NETWORK:
        return new DoubleLayeredNeuralNetwork();
    case NEAREST_NEIGHBOURS:
        return new NearestNeighbours();
    case IDENTITY:
        return new IdentityClassifier();
    }
    return null; // If I comment out this line I get compilation error
}

See the comment. I would expect that Unreachable code error will be reported for this line. Instead I get Method must return value error if I comment out this line. However, there is no way the program flow will pass through there.

I even assumed it would be a guard case for the case of null value passed-in, but as expected this triggers NullPointerException for the switch condition.

I do not use switch very often, probably I am missing something here. Can somebody please try to help understand this behaviour?

Upvotes: 2

Views: 605

Answers (2)

Paul Vargas
Paul Vargas

Reputation: 42050

That question is interesting...

We have something like this and the compiler is happy!

public enum Coin {
     PENNY,
     NICKEL,
     DIME,
     QUARTER;
}

private enum CoinColor { COPPER, NICKEL, SILVER }
private static CoinColor color(Coin c) {
    switch(c) {
        case PENNY:
            return CoinColor.COPPER;
        case NICKEL:
            return CoinColor.NICKEL;
        case DIME: case QUARTER:
            return CoinColor.SILVER;
        default:
            throw new AssertionError("Unknown coin: " + c);
    }
}

The Java Languaje Specification says:

A Java compiler is encouraged (but not required) to provide a warning if a switch on an enum-valued expression lacks a default label and lacks case labels for one or more of the enum type's constants. (Such a statement will silently do nothing if the expression evaluates to one of the missing constants.)

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533750

That is correct behaviour as you do not have a default case statement. The problem is that you could add an value to the enum later and not re-compile the code which uses it. By forcing you to always handle when it is not one of the values, this is covered.

BTW: classifier could be null which is another option switch doesn't handle unfortunately.

Upvotes: 4

Related Questions