Search code examples
javaintellij-ideaswitch-statement

What are the benefits of enhanced switch?


Recently we upgrade our code base from Java 8 to Java 17. Since then, IntelliJ IDEA warns about old switch-case statements:

Switch statement can be replaced with enhanced 'switch'

What are the benefits of the enhanced switch, besides readability?

Example: java 8 switch:

        switch (foo) {
            case "bla": return 1;
            case "bla_bla": return 2;
        }

after accepting Switch statement can be replaced with enhanced 'switch' it looks like that:

        switch (foo) {
            case "bla" -> { return 1; }
            case "bla_bla" -> { return 2; }
        }

Solution

  • IntelliJ blogpost talks about three benefits of the enhanced switch:

    1. Concise code.
    2. Can return a value.
    3. No need to use break. In absence of a break statement, the control doesn’t fall through the switch labels which helps avoid logical errors.

    In your particular example, you are already returning from the switch statement and the enhanced switch statement might not offer much. The enhanced switch improves the code when the old switch uses value assignments and breaks. For example:

    int height = 0; 
        switch (size) {
            case S:
                height = 18;
                // missing break (bug)
            case M:
                height = 20;
                break;
            case L:
                height = 25;
                break;
        }
    

    which enhanced to:

    int height = switch (size) {
            case S -> 18;
            case M -> 20;
            case L -> 25;
        }
    

    However, if your wish is to no longer get this warning, it is possible to turn it off in IntelliJ IDEA. To do so, open Preferences, and go to Editor -> Inspections (I'm using version 2023.1). Search for (part of) the warning (Switch statement can be replaced with enhanced 'switch') and de-select it.