S1481 false positive with pattern matched sealed class

Please provide

  • Operating system: macOS Sonoma
  • SonarLint plugin version:
  • Programming language you’re coding in: Java
  • Is connected mode used: No
    • Connected to SonarCloud or SonarQube (and which version):

And a thorough description of the problem / question:

If you are using pattern matching in JDK21 to switch over a sealed class, as far as I am aware, the Java compiler requires that you declare a local variable for each case, even if the value is unused. Take the following contrived example:

sealed interface InventoryItem {
  record Bicycle(FrameSize size) implements InventoryItem {}
  record Mattress(MattressSize size) implements InventoryItem {}
void addToInventory(InventoryItem item)
  switch (item)
    case Bicycle ignored ->
        // do something that doesn't make use of 'ignored'

If you remove the local variable ‘ignored’ above, the compiler will complain. However, if you keep the variable, SonarLint will complain that it is unused.

Hi @cssprs,

Thank you for reporting!
We are aware of this issue, and it is already fixed, as you can see here: [SONARJAVA-4907] - Jira

The fix will be added to the new version of SonarLint, so keep an eye on it to update as soon as it is released.

All the best,