Effective Enums in Kotlin with reverse lookup?

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

    A slightly extended approach of the accepted solution with null check and invoke function

    fun main(args: Array) {
        val a = Type.A // find by name
        val anotherA = Type.valueOf("A") // find by name with Enums default valueOf
        val aLikeAClass = Type(3) // find by value using invoke - looks like object creation
    
        val againA = Type.of(3) // find by value
        val notPossible = Type.of(6) // can result in null
        val notPossibleButThrowsError = Type.ofNullSave(6) // can result in IllegalArgumentException
    
        // prints: A, A, 0, 3
        println("$a, ${a.name}, ${a.ordinal}, ${a.value}")
        // prints: A, A, A null, java.lang.IllegalArgumentException: No enum constant Type with value 6
        println("$anotherA, $againA, $aLikeAClass $notPossible, $notPossibleButThrowsError")
    }
    
    enum class Type(val value: Int) {
        A(3),
        B(4),
        C(5);
    
        companion object {
            private val map = values().associateBy(Type::value)
            operator fun invoke(type: Int) = ofNullSave(type)
            fun of(type: Int) = map[type]
            fun ofNullSave(type: Int) = map[type] ?: IllegalArgumentException("No enum constant Type with value $type")
        }
    }
    

提交回复
热议问题