Enum Reverse Lookup in Kotlin

Enum Reverse Lookup in Kotlin


Kotlin offers the possibility to assign enumeration values to an enumeration type:

enum class Currency(val symbol: String) {

    override fun toString(): String {return this.symbol}
By selecting the enumeration type, its value can be returned:
Currency.valueOf("DOLLAR") // returns the enumeration value “$”
But Kotlin does not offer a native function if you want to start from a value and conclude to the corresponding entry. So, you have to iterate over all enumeration types and compare the value with the searched value:
Currency.values().firstOrNull {currency -> currency.symbol == "$"} // returns the enumeration type DOLLAR

This kind of solution can be found searching the web in one way or another and it does what it is supposed to do. But do you want to iterate over all enumerations every time and compare values? What about a more elegant solution?


We extend our enumeration class with a Companion Object:

companion object {
    private val mapping = values().associateBy(Currency::symbol)
    fun fromSymbol(symbol: String) = mapping[symbol]

The function associateBy() returns a map<K, T>. More precisely a LinkedHashMap where K is the enumeration value and T is our enumeration type. The function "fromSymbol()" takes the enumeration value as argument and returns the matching enumeration type. Accessing the enumeration type via the enumeration value is no longer done by iterating in O(n), but by a hash lookup in the static map in O(1).

With this extension, the reverse lookup can be done as follows:

Currency.fromSymbol("$") // returns the enumeration type DOLLAR

This offers a solution with code, which is easier to read. This solution might even be more performant in terms of execution time.

Caution: If there is no 1 to 1 relation between enumeration types and enumeration values, this solution does not return the first hit but the last hit.

Wir verwenden Cookies, um unsere Webseite für Sie zu optimieren. Mit dem Besuch unserer Webseite erklären Sie sich damit einverstanden. // Our website is using cookies to improve your experience. By continuing to browse the site, you are agreeing to our use of cookies.

Weitere Informationen finden Sie in unserer Datenschutzerklärung. // For more information, please refer to our privacy policy.

contact icon

Contact us now