-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwitchPatternMatchingTest.java
More file actions
79 lines (68 loc) · 2.53 KB
/
SwitchPatternMatchingTest.java
File metadata and controls
79 lines (68 loc) · 2.53 KB
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
package jep441;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.Map;
import java.util.SequencedCollection;
import java.util.SequencedMap;
import java.util.TreeMap;
import org.junit.jupiter.api.Test;
public class SwitchPatternMatchingTest {
@Test
void testPatternMatching() {
assertThat(getTypename(List.of())).isEqualTo("SequencedCollection type");
assertThat(getTypename(new TreeMap<>())).isEqualTo("SequencedMap type");
assertThat(getTypename(Map.of())).isEqualTo("unknown type");
assertThat(getTypename(null)).isEqualTo("NULL");
}
private String getTypename(Object c) {
return switch(c) {
// now you can use null as a selector
case null -> "NULL";
// you can use types as selector too
case SequencedCollection sc -> "SequencedCollection type";
case SequencedMap sm -> "SequencedMap type";
// default statement is required to cover all possible cases
default -> "unknown type";
};
}
// you can use `case` statement within switch
@Test
void testCaseRefinement() {
assertThat(getStandardizedPrompt("Yes")).isEqualTo("true");
assertThat(getStandardizedPrompt("No")).isEqualTo("false");
assertThat(getStandardizedPrompt("Hello")).isEqualTo("undefined prompt");
}
private String getStandardizedPrompt(Object prompt) {
return switch(prompt) {
case String s
when s.equalsIgnoreCase("true")
|| s.equalsIgnoreCase("yes")
|| s.equalsIgnoreCase("y") -> "true";
case String s
when s.equalsIgnoreCase("false")
|| s.equalsIgnoreCase("no")
|| s.equalsIgnoreCase("n") -> "false";
default -> "undefined prompt";
};
}
/* relaxed code syntax for enum case selector
you can directly use enum types in case statements without prior disambiguation of the type
* */
@Test
void testRelaxedEnumSelector() {
assertThat(toStringForm(IndividualContributor.L2)).isEqualTo("IC-L2");
assertThat(toStringForm(IndividualContributor.L3)).isEqualTo("IC-L3");
}
sealed interface EmployeeType { }
enum IndividualContributor implements EmployeeType { L1, L2, L3}
enum Manager implements EmployeeType {}
private String toStringForm(EmployeeType etype) {
return switch (etype) {
case IndividualContributor.L1 -> "IC-L1";
case IndividualContributor.L2 -> "IC-L2";
case IndividualContributor.L3 -> "IC-L3";
case Manager m -> "Manager";
default -> throw new IllegalArgumentException("unknown type: " + etype);
};
}
}