Effective Enums in Kotlin with reverse lookup?

后端 未结 12 1725
野性不改
野性不改 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:10

    First of all, the argument of fromInt() should be an Int, not an Int?. Trying to get a Type using null will obviously lead to null, and a caller shouldn't even try doing that. The Map has also no reason to be mutable. The code can be reduced to:

    companion object {
        private val map = Type.values().associateBy(Type::value)
        fun fromInt(type: Int) = map[type]
    }
    

    That code is so short that, frankly, I'm not sure it's worth trying to find a reusable solution.

提交回复
热议问题