I'm developing with java 17 in IntelliJ 2022.2.
In some cases 'switch' expression does not cover all possible input values is shown, but in some not. I'd like to figure out why.
Let's assume that entityType is an enum with 3 values and I'm adding 4th one TYPE_D. So I expect to see 'switch' expression does not cover all possible input values errors where I use this enum in switch.
When it is shown:
public Map<String, String> getRecordDetails() {
return switch (entityType) {
case TYPE_A -> Map.of("A","A");
case TYPE_B -> Map.of("B","B");
case TYPE_C -> Map.of("C","C");
};
}
not shown:
public String getRecordDetails() {
StringBuilder stringBuilder = new StringBuilder();
switch (entityType) {
case TYPE_A -> stringBuilder.append("A");
case TYPE_B -> stringBuilder.append("B");
case TYPE_C -> stringBuilder.append("C");
};
return stringBuilder.toString();
}
I see it is related when I do return of switch case, but why it is not shown when I have switch case inside of function's code?
When you use a
switchas part of areturn, it is a switch expression. But if you just put theswitchrandomly in the middle of a method, it is parsed as a switch statement. These have different rules. Importantly, switch expressions need to be exhaustive.From the Java Language Specification:
On the other hand, switch statements do not have this restriction.
Intuitively, expressions have to evaluate to a value, but statements don't have to. Therefore, switch expressions have to cover all cases. If they don't, then there will be situations where it can't evaluate to anything.
In the preview specifications of later versions of Java, the idea of an "exhaustive switch" is more clearly defined, because they now need to support pattern matching among other things.
And later,