Using switch expressions

Here's an example of a traditional switch construct that is modifying a variable based on an enum value passed to a method:

enum SingleUsePlastic {STRAW, BAG, SPOON, FORK, KNIFE, PLATE, BOTTLE}; 
 
class Planet { 
    private static long damage; 
    public void use(SingleUsePlastic plastic) { 
        switch(plastic) { 
            case STRAW :    damage += 10; 
                            break; 
            case BAG   :    damage += 11; 
                            break; 
            case SPOON :    damage += 7; 
                            break; 
            case FORK  :    damage += 7; 
                            break; 
            case KNIFE :    damage += 7; 
                            break; 
            case PLATE :    damage += 15; 
                            break; 
            case BOTTLE:    damage = 20; 
                            break; 
        } 
    } 
} 

Let's see how the preceding code changes if we use switch expressions:

damage += switch(plastic) { 
                case STRAW -> 10; 
                case BAG -> 11; 
                case SPOON, FORK, KNIFE -> 7; 
                case PLATE -> 15; 
                case BOTTLE -> 20; 
          }; 

Let's compare the new switch expressions with traditional switch statements. The code in the preceding block, which uses switch expressions, is a lot more concise. You define what to execute on the right of the arrow (->). Also, you no longer need break statements in each switch branch. There's less boilerplate and less likelihood of accidental errors from missing break statements.

The following diagram highlights the changes:

These switch expressions are in addition to traditional switch constructs. They are not here to replace existing switch constructs.

A switch expression offers multiple benefits and features:

  • Unlike a switch statement, a switch expression can return a value
  • The return value for a switch branch is defined to the right of ->
  • The same switch branch can define multiple labels that are separated using ,
  • There isn't any default fall through of the control across switch branches
  • The code is less verbose

Let's work with the finer details of switch expressions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.39.133