Effective Enums in Kotlin with reverse lookup?

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

    True Idiomatic Kotlin Way. Without bloated reflection code:

    interface Identifiable {
    
        val id: T
    }
    
    abstract class GettableById(values: Array) where T : Number, R : Enum, R : Identifiable {
    
        private val idToValue: Map = values.associateBy { it.id }
    
        operator fun get(id: T): R = getById(id)
    
        fun getById(id: T): R = idToValue.getValue(id)
    }
    
    enum class DataType(override val id: Short): Identifiable {
    
        INT(1), FLOAT(2), STRING(3);
    
        companion object: GettableById(values())
    }
    
    fun main() {
        println(DataType.getById(1))
        // or
        println(DataType[2])
    }
    

提交回复
热议问题