How to obtain all subclasses of a given sealed class?

后端 未结 4 1708
孤街浪徒
孤街浪徒 2021-02-02 05:56

Recently we upgraded one of our enum class to sealed class with objects as sub-classes so we can make another tier of abstraction to simplify code. However we c

4条回答
  •  悲哀的现实
    2021-02-02 06:45

    Full example:

    sealed class State{
        companion object {
            fun find(state: State) =
                State::class.sealedSubclasses
                        .map { it.objectInstance as State}
                        .firstOrNull { it == state }
                        .let {
                            when (it) {
                                null -> UNKNOWN
                                else -> it
                            }
                        }
        }
        object StateA: State()
        object StateB: State()
        object StateC: State()
        object UNKNOWN: State()
    
    }
    

提交回复
热议问题