File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .time .LocalDate ;
2
+ import java .time .YearMonth ;
3
+ import java .time .ZoneOffset ;
4
+ import java .time .temporal .ChronoUnit ;
5
+ import java .util .stream .Stream ;
6
+
7
+ /**
8
+ * Run: `java --enable-preview --source 18 <FileName.java>`
9
+ */
10
+ public class SwitchWithPatternMatchingSecondPreview {
11
+ public static void main (String [] args ) {
12
+ System .out .println (stringify (42 ));
13
+ System .out .println (stringify (-42 ));
14
+ System .out .println (stringify ("Some text" ));
15
+ System .out .println (stringify ("" ));
16
+ }
17
+
18
+ static String stringify (Object value ) {
19
+ return switch (value ) {
20
+ // the constant must be before the guarded pattern (otherwise it will never hit)
21
+ case 42 -> "42 is the answer" ;
22
+ case Integer i && i < 0 -> "negative number" ;
23
+ // this must be after because it will match all integers
24
+ case Integer i -> "some number" ;
25
+
26
+ case String s && s .isEmpty () -> "empty string" ;
27
+ case String s && s .length () > 50 -> "long string" ;
28
+ // this must be after because it will match all strings
29
+ case String s -> "non-empty string" ;
30
+
31
+ default -> "unhandled type" ;
32
+ };
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments