Effective Enums in Kotlin with reverse lookup?

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

    It makes not much sense in this case, but here is a "logic extraction" for @JBNized's solution:

    open class EnumCompanion(private val valueMap: Map) {
        fun fromInt(type: T) = valueMap[type]
    }
    
    enum class TT(val x: Int) {
        A(10),
        B(20),
        C(30);
    
        companion object : EnumCompanion(TT.values().associateBy(TT::x))
    }
    
    //sorry I had to rename things for sanity
    

    In general that's the thing about companion objects that they can be reused (unlike static members in a Java class)

提交回复
热议问题