Using pattern matching with switch constructs

The switch statement seems to be one of the best constructs that can use pattern matching. At present, a switch construct can match primitive literal values (excluding long, float, and double), String, and enum constants.

If a case label can specify a pattern, the code in the preceding section (the one that uses multiple instances of object checking and value extraction) can be modified as follows:

void dyingFish(Object obj) { 
    switch (obj) { 
        case Ocean o:   System.out.println(o.getBottles()); 
                        break; 
        case Sea sea:   System.out.println(sea.getDeadFish()); 
                        break; 
        case River riv: if (riv.getPlasticBags() > 100) { 
                            System.out.println("Humans enjoy! Fish die!"); 
                        } 
                        break; 
    } 
} 

With pattern matching, the business logic takes the limelight. It also reduces the complexity of the syntax, which improves code readability. The preceding code is also optimizable because we are likely to dispatch in O(1) time.

Under pattern matching, work is also being done on the deconstruction pattern (which is the opposite of instance construction).
..................Content has been hidden....................

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