5
5
public class SwitchExpressions {
6
6
public static void main (String [] args ) {
7
7
// Now switch expressions are final o/
8
+ // kinds of switch case statements
9
+ System .out .println (oldWay (Mood .BAD ));
10
+ System .out .println (lambdaWay (Mood .GOOD ));
11
+ System .out .println (mixingSwitchKinds (Mood .REGULAR ));
8
12
9
13
FeaturePhase switchWithPatternMatching = FeaturePhase .FINAL ;
10
14
@@ -15,9 +19,77 @@ public static void main(String[] args) {
15
19
16
20
System .out .println ("Switch expressions with pattern matching: " + message );
17
21
}
22
+
23
+ static String oldWay (Mood mood ) {
24
+ // old way (set a var or return method value)
25
+ switch (mood ) {
26
+ // we use lambda here, swith isn't used in a statement
27
+ // error: not a statement
28
+ // case GOOD -> "All right";
29
+
30
+ // can mix kinds of switch
31
+ // error: different case kinds used in the switch
32
+ // case GOOD -> { return "All right"; }
33
+
34
+ case GOOD : return "All right" ;
35
+ case REGULAR : return "Can do better" ;
36
+ default : return "Let's improve!" ;
37
+ }
38
+ }
39
+
40
+ static String lambdaWay (Mood mood ) {
41
+ return switch (mood ) {
42
+ case GOOD -> {
43
+ // yield can only be used in a switch statement
44
+ yield "All right" ;
45
+ }
46
+ // lambda without block requires semi-colon
47
+ case REGULAR -> "Can do better" ;
48
+ default -> "Let's improve!" ;
49
+ };
50
+ }
51
+
52
+ static String mixingSwitchKinds (Mood mood ) {
53
+ String message ;
54
+ switch (mood ) {
55
+ // here we can return because isn't a switch statement
56
+ case BAD -> {
57
+ return "Not today" ;
58
+ }
59
+ // we still can change vars
60
+ default -> {
61
+ message = "We still can go" ;
62
+ }
63
+ }
64
+
65
+ // switch used in a statement
66
+ var result = switch (mood ) {
67
+ // we cannot mix return here (will cause `not a statement` in the following cases)
68
+
69
+ case GOOD -> {
70
+ // we cannot return when switch is used as statement
71
+ // error: attempt to return out of a switch expression
72
+ // return "All right";
73
+ yield "All right" ;
74
+ }
75
+
76
+ // can mix kinds of switch
77
+ // error: different case kinds used in the switch
78
+ // default: return "Still can improve";
79
+
80
+ default -> "Still can improve" ;
81
+ };
82
+ return result ;
83
+ }
18
84
}
19
85
20
86
enum FeaturePhase {
21
87
PREVIEW ,
22
88
FINAL
23
- }
89
+ }
90
+
91
+ enum Mood {
92
+ GOOD ,
93
+ REGULAR ,
94
+ BAD
95
+ }
0 commit comments