A complete switch of enumeration in Java will result in a “missing return statement” error

Suppose we have a switch statement, which completely covers all possible cases of enumeration parameters, and also carries out null check. It will not be compiled into the reason of "missing return statement"

enum Foo {ONE,TWO}

int fooToInt(Foo foo) {
    if (foo == null) {
        throw new NullPointerException();
    }
    switch (foo) {
        case ONE: return 1;
        case TWO: return 2;
    }
}

I know that throwing exceptions from the default or after enumeration, or accessing enumerated elements instead of switching will solve the problem But I don't understand the technical reason for this behavior: obviously, there is no possible branch, which will not lead to return or throw In some cases, it would be great to check at compile time whether all cases are covered

Solution

The compiler does not check whether you have listed all constants in foo as case blocks, resulting in an error

Suppose foo is defined as:

enum Foo {ONE,TWO,THREE}

So, if you pass foo What will your method return with three as a parameter?

As an alternative to switching methods, you can add an int member to the foo enumeration and set the corresponding number for each constant:

enum Foo {
    ONE(1),TWO(2);

    int value;
    Foo(int value) {
        this.value = value;
    }
}

In this way, you don't need a switch. The compiler will ask you to set a corresponding number for any possible new foo constant

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>