Is there an annotation or another method to turn the non-exhaustive switch statement warning into an error? I want a certain method or class to produce an error if not all values have been handled in the switch properly.
Example:
public enum E {
A,
B
}
and somewhere else in the code there is a switch on that enum like so
switch (enumValue) {
case A: /* do something */ break;
}
Java will give you a warning that this switch does not handle all the enum values. I want to turn this warning into an error (permanently, regardless of individual IDE settings).
Please keep in mind that I cannot change the original enum
in this case, so I want the compiler to enforce it.
I recently started learning Swift and came across a Swift switches, it seems that switches must be exhaustive in Swift, for example. let nums = 1...5 for num in nums { switch num { case 2: // Do Something // Will throw a comilation error unless default: was added } }
The result of a switch expression is the value of the expression of the first switch expression arm whose pattern matches the input expression and whose case guard, if present, evaluates to true. The switch expression arms are evaluated in text order.
The switch expression arms, separated by commas. Each switch expression arm contains a pattern, an optional case guard, the => token, and an expression. At the preceding example, a switch expression uses the following patterns:
While having to update switch statements can often indicate code that isn't so great, typescript contains a language construct to be able to write an exhaustive switch statement, though the use of the never type. Now lets look at how we can apply this knowledge.
I know this is an old thread but there is a new answer in the latest JDKs:
Switch Expressions must be exhaustive and are available as a preview language feature in JDK 12 and 13.
https://openjdk.java.net/jeps/354
This means you can modify switch statements that require validation to be switch expressions while other switch statements will continue to work as intended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With