Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 191

Applying a case Block

Оглавление

A switch expression supports both an expression and a block in the case and default branches. Like a regular block, a case block is one that is surrounded by braces ({}). It also includes a yield statement if the switch expression returns a value. For example, the following uses a mix of case expressions and blocks:

int fish = 5; int length = 12; var name = switch(fish) { case 1 -> "Goldfish"; case 2 -> {yield "Trout";} case 3 -> { if(length > 10) yield "Blobfish"; else yield "Green"; } default -> "Swordfish"; };

The yield keyword is equivalent to a return statement within a switch expression and is used to avoid ambiguity about whether you meant to exit the block or method around the switch expression.

Referring to our second rule for switch expressions, yield statements are not optional if the switch statement returns a value. Can you see why the following lines do not compile?

10: int fish = 5; 11: int length = 12; 12: var name = switch(fish) { 13: case 1 -> "Goldfish"; 14: case 2 -> {} // DOES NOT COMPILE 15: case 3 -> { 16: if(length > 10) yield "Blobfish"; 17: } // DOES NOT COMPILE 18: default -> "Swordfish"; 19: };

Line 14 does not compile because it does not return a value using yield. Line 17 also does not compile. While the code returns a value for length greater than 10, it does not return a value if length is less than or equal to 10. It does not matter that length is set to be 12; all branches must yield a value within the case block.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх