Effective Enums in Kotlin with reverse lookup?

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

    Based on your example, i might suggest removing the associated value and just use the ordinal which is similar to an index.

    ordinal - Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

    enum class NavInfoType {
        GreenBuoy,
        RedBuoy,
        OtherBeacon,
        Bridge,
        Unknown;
    
        companion object {
            private val map = values().associateBy(NavInfoType::ordinal)
            operator fun get(value: Int) = map[value] ?: Unknown
        }
    }
    

    In my case i wanted to return Unknown if the map returned null. You could also throw an illegal argument exception by replacing the get with the following:

    operator fun get(value: Int) = map[value] ?: throw IllegalArgumentException()
    

提交回复
热议问题