What are switch expressions
Switch expressions were introduced in December 2017 in JEP 325, which was targeted for JDK 12 in August 2018.
The benefits of switch expressions are:
- They make code more robust and easy to read
- They always evaluate to a single value
- Labels in switch expressions eliminate the need for break statements to prevent fall-through, which is error-prone
- No need to store the result in a variable
Of course, there are more benefits than I can list here.
Modern IDEs like IntelliJ will sometimes suggest that you convert a switch statement to a switch expression.
Let’s see some examples.
Example
Using yield
- It’s recommended you use “case L ->” since it’s easy to forget to add break or yield statements with the “case L:” labels.
- The yield statement distinguishes switch statements from switch expressions. A switch statement can have break but not a switch expression, and vice versa.
- Statement groups must contain a yield.
- Yields are useful when your case is a block, and you need to return the value.
A note on exhaustiveness
- The switch expression is exhaustive, unlike the switch statement. This means that all possible values in the enum must have a matching switch label.
- Hence, a switch expression will normally require a default clause. For enum switch expressions, the compiler will insert an implicit default case.
- The good news is that the compiler will catch exhaustiveness errors for you.