-1

I have declared this enum class:

public enum class RoleName {
    Worker,
    Boss
}

which I want to use it in a switch / case

switch (requestRole.getName()) {
    case RoleName.Worker.name():

but I have this compilation error

constant expression required 

and if I remove class I got this IntelliJ IDEA error: 'class' keyword is expected after 'enum;

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Sandro Rey
  • 2,429
  • 13
  • 36
  • 80

1 Answers1

4

Two mistakes here:

  1. The definition of the enum shouldn't have class in it. As a rule of thumb, the constants should be uppercase.

    enum RoleName {
        WORKER,
        BOSS;
    }
    
  2. RoleName.Worker.name() isn't allowed as a case expression since it's not a constant expression. You could transform requestRole.getName() into a RoleName and use it as a switch expression.

    switch (RoleName.valueOf(requestRole.getName())) {
        case WORKER: /* ... */ break;
    }
    
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • #2 is not exactly the same code, because if value of `requestRole.getName()` doesn't match an enum name, then question code will work (go to `default` if any), and this code will throw `IllegalArgumentException`. – Andreas Oct 16 '19 at 11:19
  • I spent looking for a valid DUP candidate ... but hey, all of these questions are slightly different. Go make this the DUP candidate for switch case calling a method! – GhostCat Oct 16 '19 at 11:19
  • @CarlosHeuberger because `requestRole` isn't a `RoleName` – Andrew Tobilko Oct 16 '19 at 11:39
  • @CarlosHeuberger `getName` isn't a enum method – Andrew Tobilko Oct 16 '19 at 11:42
  • 1
    It’s actually `case WORKER:`. Java doesn’t allow qualified enum constants in `case` statements. – VGR Oct 16 '19 at 13:27