Defining local variables in a switch branch

It is possible to define variables that are local to a switch branch. To do so, a switch branch can define a block of code to execute for a matching case label. To return the value from the branch, it can include a break statement specifying the value to return. 

Let's modify the code in the preceding example to define a code block, as follows:

class Planet { 
    private static long damage; 
    public void use(SingleUsePlastic plastic) { 
        damage += switch(plastic) { 
            case STRAW -> 10; 
            case BAG -> 11; 
            case SPOON, FORK, KNIFE -> 7; 
            case PLATE -> { 
                                int radius = 20;  // Local variable           
break (radius < 10 ? 15 : 20); // Using
// break to return
// a value } case BOTTLE -> 20; }; } }

The scope and accessibility of the local variable, radius, are limited to the switch branch, in which it is defined.

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

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