google / error-prone

Catch common Java mistakes as compile-time errors

Home Page:https://errorprone.info

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

UnnecessaryDefaultInEnumSwitch does not work with enhanced switch statement for cases with multiple values

robinst opened this issue · comments

With UnnecessaryDefaultInEnumSwitch set to ERROR, the following code:

enum Type {
    FOO, BAR, BAZ
}

public static void main(String[] args) {
    var type = Type.valueOf(args[0]);
    switch (type) {
        case FOO -> {
            System.out.println("Hi foo");
        }
        case BAR, BAZ -> {
        }
        default -> throw new AssertionError(type);
    }
}

Does not error but I would expect it to.

Note that changing the case BAR, BAZ into separate cases like this:

        case BAR -> {
        }
        case BAZ -> {
        }

Makes the check work as expected:

src/main/java/example/Hello.java:18: error: [UnnecessaryDefaultInEnumSwitch] Switch handles all enum values: the default case can be omitted to enable enforcement at compile-time that the switch statement is exhaustive.
            default -> throw new AssertionError(type);
            ^
    (see https://errorprone.info/bugpattern/UnnecessaryDefaultInEnumSwitch)

This is with bazel version 7.2.0. I'm not sure what version of error-prone that is (not super familiar with bazel).

I pushed a minimal example repo for this here: https://github.com/robinst/error-prone-unnecessary-default