Invalid pattern match guard suggestion java:S6916

Please provide

  • Operating system: macOS sonoma
  • SonarLint plugin version: 10.12.0.79769
  • IntelliJ version: Ultimate 2024.1.6
  • Programming language you’re coding in: JDK 21
  • Is connected mode used: No
    • Connected to SonarCloud or SonarQube (and which version):

And a thorough description of the problem / question:

I’m switching over an enum using the new pattern matching syntax. SonarLint is incorrectly suggesting that I replace an if statement with a pattern match guard, and, when I apply the suggestion, it creates code that cannot be compiled by JDK 21.

var user; // assume this is specified
switch (anEnum) {
   case A_CASE -> {
      if (user.isVip()) // <-- triggers suggestion
      {
         // do something
      }
   }
}

Applied suggestion is as follows:

var user; // assume this is specified
switch (anEnum) {
   case A_CASE when user.isVip() -> { // <-- Compiler blows up on this
      
   }
}

I’m not intimately familiar with all the variations that the compiler supports, but it appears that the case statement would need to be written as follows:

  case MyEnumClass aCase when aCase == A_CASE && user.isVip() ->
1 Like

Hey @cssprs

Thanks for the report! I believe we’re already tracking this at SONARJAVA-4962.