Skip to content

[java] False positive violation of SwitchStmtsShouldHaveDefault when using local variable inference #2743

@vojtapol

Description

@vojtapol

Affects PMD Version: 6.26.0

Description:

When using local variable inference PMD can't determine that a switch variable is an enum and requires the default branch.

Code Sample demonstrating the issue:

enum Type {
  CAT, DOG, COW
}

...

for (var animal : getAnimals()) {
    switch (animal.getType()) { // false violation
        case CAT:
            // do something 1
            break;
        case DOG:
            // do something 2
            break;
        case COW:
            // do something 3
            break;
    }
}

...

    public void setValue(List<Type> list) {
        // it works with explicit types: list.forEach((Type eIn) -> {
        list.forEach(eIn -> {
            switch (eIn) {
            case CAT:
                // do something 1
                break;
            case DOG:
                // do something 2
                break;
            case COW:
                // do something 3
                break;
            });
    }

Workaround:
Either explicit type must be specified in the for-loop or default branch must be added to the switch statement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematicin:type-resolutionAffects the type resolution code

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions