Effective Enums in Kotlin with reverse lookup?

后端 未结 12 1720
野性不改
野性不改 2020-11-30 01:40

I\'m trying to find the best way to do a \'reverse lookup\' on an enum in Kotlin. One of my takeaways from Effective Java was that you introduce a static map inside the enum

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 02:14

    A variant of some previous proposals might be the following, using ordinal field and getValue :

    enum class Type {
    A, B, C;
    
    companion object {
        private val map = values().associateBy(Type::ordinal)
    
        fun fromInt(number: Int): Type {
            require(number in 0 until map.size) { "number out of bounds (must be positive or zero & inferior to map.size)." }
            return map.getValue(number)
        }
    }
    

    }

提交回复
热议问题