I have several switch statements which test an enum. All enum values must be handled in the switch statements by a case s
Functional approach with lambdas, much less code
public enum MyEnum {
FIRST,
SECOND,
THIRD;
T switchFunc(
Function first,
Function second,
Function third
// when another enum constant is added, add another function here
) {
switch (this) {
case FIRST: return first.apply(this);
case SECOND: return second.apply(this);
case THIRD: return third.apply(this);
// and case here
default: throw new IllegalArgumentException("You forgot to add parameter");
}
}
public static void main(String[] args) {
MyEnum myEnum = MyEnum.FIRST;
// when another enum constant added method will break and trigger compile-time error
String r = myEnum.switchFunc(
me -> "first",
me -> "second",
me -> "third");
System.out.println(r);
}
}