An exhaustive switch statement handles every permitted subtype in a sealed selector hierarchy. The compiler then rejects the switch when a new permitted subtype is not handled. section 8.2
Processing every Entry subtype
sealed interface Entry {} record IntEntry(int value) implements Entry {} record StringEntry(String value) implements Entry {} void processList(List<Entry> list) { for (Entry element : list) { switch (element) { case IntEntry(int number) -> processNumber(number); case StringEntry(String string) -> processString(string); } } } If another permitted Entry subtype is added, compilation fails at this switch until its case is handled. section 8.2
sealed interface Entry {}
record IntEntry(int value) implements Entry {}
record StringEntry(String value) implements Entry {}
void processList(List<Entry> list) {
for (Entry element : list) {
switch (element) {
case IntEntry(int number) -> processNumber(number);
case StringEntry(String string) -> processString(string);
}
}
}
Inspect the compact sealed hierarchy and pattern cases used to process list elements. section 8.2
