Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force exhaustive switch

Tags:

java

enums

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.

like image 324
Era Avatar asked Nov 28 '14 07:11

Era


People also ask

Do Swift switches have to be exhaustive?

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 } }

What is the result of a switch expression?

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.

What are the switch expression arms?

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:

Can you write an exhaustive switch statement in typescript?

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.


1 Answers

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.

like image 148
imoverclocked Avatar answered Sep 23 '22 06:09

imoverclocked