September 2019
Intermediate to advanced
816 pages
18h 47m
English
Before we have a brief overview of the switch expressions introduced in JDK 12, let's see a typical old-school example wrapped in a method:
private static Player createPlayer(PlayerTypes playerType) { switch (playerType) { case TENNIS: return new TennisPlayer(); case FOOTBALL: return new FootballPlayer(); case SNOOKER: return new SnookerPlayer(); case UNKNOWN: throw new UnknownPlayerException("Player type is unknown"); default: throw new IllegalArgumentException( "Invalid player type: " + playerType); }}
If we forget about default, then the code will not compile.
Obviously, the preceding example is acceptable. In the worst-case scenario, we can add a spurious variable (for example, player), some cluttering break statements, ...