Efficient enums in Kotlin: how to do reverse lookup by value?
Hello everyone! I've been writing in Kotlin recently and encountered this task.\n\nI have an enum class for order statuses:\n\n```kotlin\nenum class OrderStatus(val code: Int) {\n PENDING(1),\n PROCESSING(2),\n SHIPPED(3),\n DELIVERED(4),\n CANCELLED(5)\n}\n```\n\nFrom the database I get a numeric status code (for example, 3), and I need to get the corresponding enum value — `OrderStatus.SHIPPED`.\n\nI know that in Java they often use a static `HashMap` for reverse lookup. But in Kotlin this looks cumbersome. I tried writing an extension function:\n\n```kotlin\nfun OrderStatus.Companion.fromCode(code: Int): OrderStatus? {\n return values().find { it.code == code }\n}\n```\n\nBut this works slowly because it iterates through all values every time. For 5 statuses it's not critical
No answers yet.
Log in to leave an answer