What are sealed classes in Kotlin?

后端 未结 3 1182
无人共我
无人共我 2020-12-24 07:25

I\'m a beginner in Kotlin and recently read about Sealed Classes. But from the doc the only think I actually get is that they are exist.

The doc stated, that they are

3条回答
  •  爱一瞬间的悲伤
    2020-12-24 07:58

    If you've ever used an enum with an abstract method just so that you could do something like this:

    public enum ResultTypes implements ResultServiceHolder {
        RESULT_TYPE_ONE {
            @Override
            public ResultOneService getService() {
                return serviceInitializer.getResultOneService();
            }
        },
        RESULT_TYPE_TWO {
            @Override
            public ResultTwoService getService() {
                return serviceInitializer.getResultTwoService();
            }
        },
        RESULT_TYPE_THREE {
            @Override
            public ResultThreeService getService() {
                return serviceInitializer.getResultThreeService();
            }
        };
    

    When in reality what you wanted is this:

    val service = when(resultType) {
        RESULT_TYPE_ONE -> resultOneService,
        RESULT_TYPE_TWO -> resultTwoService,
        RESULT_TYPE_THREE -> resultThreeService
    }
    

    And you only made it an enum abstract method to receive compile time guarantee that you always handle this assignment in case a new enum type is added; then you'll love sealed classes because sealed classes used in assignments like that when statement receive a "when should be exhaustive" compilation error which forces you to handle all cases instead of accidentally only some of them.

    So now you cannot end up with something like:

    switch(...) {
       case ...:
           ...
       default:
           throw new IllegalArgumentException("Unknown type: " + enum.name());
    }
    

    Also, enums cannot extend classes, only interfaces; while sealed classes can inherit fields from a base class. You can also create multiple instances of them (and you can technically use object if you need the subclass of the sealed class to be a singleton).

提交回复
热议问题