-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathSwitchWithPatternMatchingSecondPreview.java
39 lines (35 loc) · 1.23 KB
/
SwitchWithPatternMatchingSecondPreview.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
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;
/**
* Run: `java --enable-preview --source 18 <FileName.java>`
*/
public class SwitchWithPatternMatchingSecondPreview {
public static void main(String[] args) {
System.out.println(stringify(42));
System.out.println(stringify(-42));
System.out.println(stringify("Some text"));
System.out.println(stringify(""));
System.out.println(stringify(null));
}
static String stringify(Object value) {
return switch (value) {
// the constant must be before the guarded pattern (otherwise it will never hit)
case Integer i && i == 42 -> "42 is the answer";
case Integer i && i > 0 -> "positive number";
case Integer i && i < 0 -> "negative number";
// this must be after because it will match all integers
case Integer i -> "should be 0";
case String s && s.isEmpty() -> "empty string";
case String s && s.length() > 50 -> "long string";
// this must be after because it will match all strings
case String s -> "non-empty string";
// same here
case CharSequence cs -> "any other CharSequence";
case null -> "null =s";
default -> "unhandled type";
};
}
}