-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathSwitchExpressionExample.java
105 lines (87 loc) · 2.59 KB
/
SwitchExpressionExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
public class SwitchExpressionExample {
public static void main(String ... args) {
compatibleWithOldVersion();
longVersion();
shortVersion();
switchWithReturn();
inferringType();
}
public static void compatibleWithOldVersion() {
int luckNumber = 7;
// we can use the old syntax (case:)
var wasLucky = switch (luckNumber) {
// here the fall-through happens (if there is no break or return the next case will be executed)
case 7:
break false; // break was changed to yield in Java 13
case 13:
break true;
// here we must provide a default case (compiler checks exhaustiveness)
default:
throw new IllegalArgumentException("Wrong number");
}; // switch expression needs ;
System.out.println("\nWas I lucky? " + wasLucky);
}
public static void longVersion() {
var mood = Incomes.Good;
// arrow syntax with no fall-through (only the arrow block will be executed)
var shouldIGo = switch (mood) {
// accepts multiple case labels
case Good, Regular -> {
break true;
}
case Bad -> {
break false;
}
// there is no need to use default (we covered all possible cases)
};
System.out.println("\nShould I go? " + shouldIGo);
}
public static void shortVersion() {
var mood = Incomes.Good;
// cool syntax with no fall-through (only the arrow block will be executed)
var shouldIGo = switch (mood) {
// accepts multiple case labels
case Good, Regular -> true;
case Bad -> false;
// there is no need to use default (we covered all possible cases)
};
System.out.println("\nShould I go? " + shouldIGo);
}
public static void switchWithReturn() {
var mood = Incomes.Bad;
// used as statement (there is no assign)
switch (mood) {
case Good -> {
var easy = true;
System.out.println("\nKeep working");
}
case Regular, Bad -> {
// we can now declare vars with same name (each arrow has its own scope)
var easy = true;
System.out.println("\nGo home");
/*
* we can only return inside a block and when switch
* is used as statement
*/
return;
}
}
}
public static void inferringType() {
var mood = Incomes.Good;
// compiler infers the most specific supertype
// of String and IllegalArgumentException is Serializable
// Serializable whichType // we can only use its supertype
var whichType = switch (mood) {
case Good -> "All right";
default -> new IllegalArgumentException("Not right");
};
// won't work
// System.out.println("What is the length? " + whichType.length());
}
}
enum Incomes {
Good,
Regular,
Bad
}