How to ensure completeness in an enum switch at compile time?

后端 未结 12 1023
悲&欢浪女
悲&欢浪女 2020-11-27 06:25

I have several switch statements which test an enum. All enum values must be handled in the switch statements by a case s

12条回答
  •  清歌不尽
    2020-11-27 06:49

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

    }

提交回复
热议问题