Effective Enums in Kotlin with reverse lookup?

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

    Another example implementation. This also sets the default value (here to OPEN) if no the input matches no enum option:

    enum class Status(val status: Int) {
    OPEN(1),
    CLOSED(2);
    
    companion object {
        @JvmStatic
        fun fromInt(status: Int): Status =
            values().find { value -> value.status == status } ?: OPEN
    }
    

    }

提交回复
热议问题