You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/switch/exhaustiveness.md
+41-4Lines changed: 41 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -23,10 +23,36 @@ String describe(int number) {
23
23
}
24
24
```
25
25
26
-
When you have something like an enum you don't need a `default` case
27
-
because you can handle every variant explicitly.
26
+
When you have something like an enum you might think you don't need a `default` case
27
+
because you can handle every variant explicitly.[^sometimes]
28
28
29
-
```java,no_run
29
+
```java,no_run,does_not_compile
30
+
enum Bird {
31
+
TURKEY,
32
+
EAGLE,
33
+
WOODPECKER
34
+
}
35
+
36
+
boolean isScary(Bird bird) {
37
+
switch (bird) {
38
+
case TURKEY -> {
39
+
return true;
40
+
}
41
+
case EAGLE -> {
42
+
return true;
43
+
}
44
+
case WOODPECKER -> {
45
+
return false;
46
+
}
47
+
}
48
+
}
49
+
```
50
+
51
+
This is, unfortunately, not the case for a switch statement.
52
+
You either need a `default` case or to have an explicit `case null` to handle the
53
+
possibility that the enum value is `null`.[^lies]
54
+
55
+
```java,no_run,does_not_compile
30
56
enum Bird {
31
57
TURKEY,
32
58
EAGLE,
@@ -44,6 +70,17 @@ boolean isScary(Bird bird) {
44
70
case WOODPECKER -> {
45
71
return false;
46
72
}
73
+
// Need to handle the possibility of null
74
+
// or give a "default ->"
75
+
case null -> {
76
+
// You might want to return a value or just crash
77
+
return false;
78
+
}
47
79
}
48
80
}
49
-
```
81
+
```
82
+
83
+
[^sometimes]: This is sometimes the case! It is really just this specific form of switch that has this restriction.
84
+
85
+
[^lies]: Remember at the very start when I said I was going to lie to you? This is one of those lies. The real reason for this restriction has to do with how Java compiles switch statements and a concept called "separate compilation." Basically
86
+
even though we know you covered all the enum variants, Java still makes you account for if a new enum variant was added later on. It doesn't do this for all forms of `switch` though.
0 commit comments