Reverse Lookup Enums with Kotlin

Kotlin has a lot of super cool things, and Enum Classes are one of them.

We initialize our enums with a string value. Yet a problem arose when we wanted to find the enum using that string value. What’s the best way to find an enum when you have it’s value?

enum class TransmissionType(val dataKey: String) {

val myValue = "MT"
// how do I use "MT" to get MANUAL_TRANSMISSION ?

It turns out there is a idiomatic way to achieve this using associateBy and the get operator. This technique works really well.

Instead of writing a function to find your enum: MyEnumClass.findMyEnum("AT")
You have code like this: MyEnumClass["AT"]

Instead of explaining it, I’ll just show you an example with some tests.

import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

enum class TransmissionType(val dataKey: String) {

    companion object {
        private val map = TransmissionType.values().associateBy(TransmissionType::dataKey)
        operator fun get(value: String) = map[value]

class EnumAssociateByTest {
    fun getDataKey() {
        val equipmentType = TransmissionType.MANUAL_TRANSMISSION
        assertEquals(equipmentType.dataKey, "MT")

    fun getTypeFromDataKey() {
        // WHEN I try to get an transmission type based on its `dataKey`
        val equipment = TransmissionType["AT"]

        // THEN I get the expected result
        assertEquals(TransmissionType.AUTOMATIC_TRANSMISSION, equipment!!)

    fun getNullFromNonExistentType() {
        // WHEN I try to get an equipment type using a non-existing `dataKey`
        val equipment = TransmissionType["nope"]
        // THEN I get the expected null value

When learning new techniques, I like to build little examples in IntelliJ with tests.
I’ve found it makes it lot faster to play around than in Android Studio.