Exhaustive cases

A switch expression can be used to return a value or just execute a set of statements, like the traditional switch statement.

When you are using a switch expression to return a value that is used to assign a value to a variable, its cases must be exhaustive. This essentially means that, whatever value you pass to the switch argument, it must be able to find an appropriate branch to execute. A switch expression can accept arguments of the byte, short, int, Byte, Short, Integer, or String types or enums. Of these, only an enum has exhaustive values.

In the following example, a switch expression is being used to assign a value to the damage variable. Since there is no matching branch to execute for the PLATE value, this code won't compile:

class Planet { 
    private static long damage; 
    public void use(SingleUsePlastic plastic) { 
        damage += switch(plastic) { 
            case SPOON, FORK, KNIFE -> 7; 
        }; 
    } 
} 

To compile the preceding code, you can either add the switch branch with the case label, PLATE, or add a default branch, as follows:

class Planet { 
    private static long damage; 
    public void use(SingleUsePlastic plastic) { 
        damage += switch(plastic) { 
            case SPOON, FORK, KNIFE -> 7; 
// Adding (1) or (2), or both will enable the code to
// compile
case PLATE -> 10; // line number (1)
default -> 100; // line number (2) }; } }

For switch arguments such as primitive types, wrapper classes, or String classes, which don't have an exhaustive list of values, you must define a default case label (if you are returning a value from switch expressions), as follows:

String getBook(String name) {
String bookName = switch(name) { case "Shreya" -> "Harry Potter";
case "Paul" -> "Management tips";
case "Harry" -> "Life of Pi";
default -> "Design Patters - everyone needs this"; };
return bookName;
}

Let's work with the second situation where you are not using switch expressions to return a value. The following code modifies the getBook() method from the preceding code. Though switch expressions use the new syntax (using -> to define the code to execute), it is not returning a value. In such a case, the cases of a switch expression need not be exhaustive:

 String getBook(String name) {
String bookName = null;
switch(name) { // NOT returning
// a value
case "Shreya" -> bookName = "Harry Potter";
case "Paul" -> bookName = "Management tips";
case "Harry" -> bookName = "Life of Pi"; // default case
// not included
}
return bookName;
}
When you use switch expressions to return a value, its cases must be exhaustive, otherwise, your code won't compile. When you are using switch expressions to execute a set of statements without returning a value, it's cases might not be exhaustive.

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

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