Necessary empty block in when-else is falsely flagged

  • What language is this for?

  • Which rule?
    kotlin:S108 “nested block of code should not be left empty”

  • Why do you believe it’s a false-positive/false-negative?
    “when” statements are sometimes required to be exhaustive, for instance when the subject is an enum, even if only certain cases should actually trigger any code.
    This is commonly and cleanly solved using an “else” clause with an empty body block as a catch-all.

    Sonar, however, flags the block with “Either remove or fill this block of code.”
    This is misguided:

    • Without the block (or the else) the code will not compile.
    • There is nothing sensible to fill it with (and no, comments or dummy code to appease a misguided tool do not constitute sensible content)

    It is possible to use “else → Unit” in stead of “else → {}” to work around this flag, but it is far from clear that this is in any way better or more readable code. “{}” communicates “do nothing” very clearly. And this is in any case not what the warning is advocating.

  • Are you using

    • SonarLint in IntelliJ IDEA 2022.3.2
      • connected to SonarQube Community EditionVersion 9.3
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

            SATURDAY, SUNDAY -> println("No work!")
            else -> {}
1 Like

Hi Joachim, thank you for the report. I believe you are correct as in such cases the best way to describe that you don’t want to perform operations for all the other cases it’s an empty else block. I created a ticket to add this case as an exception to the rule

Have a nice day

Any update on this? Given there are already exceptions to this rule, I’m hopeful it’s easy to extend to the when case.

1 Like

Hi Sebastian, we have not had the chance yet to work on this ticket. You can track its progress from the link I shared previously, whenever we will fix it, you will be able to see it there!