hanki.dev

kotlin enum creation: handle unknown values

When dealing with enums in Kotlin, if you have a set of predefined constant values and another case where the value is unknown, you can easily handle the unknown case by utilizing the invoke function during enum creation.

enum class ExampleEnum(val code: String) {
    EXAMPLE_A("EXA"),
    EXAMPLE_B("EXB"),
    EXAMPLE_C("EXC"),
    EXAMPLE_D("EXD"),
    UNKNOWN("XXX");

    companion object {
        operator fun invoke(code: String?): ExampleEnum = values().find { it.code == code } ?: UNKNOWN
    }
}

Now just create the enum normally like val foo = ExampleEnum("bar") and if the code doesn't match any of the values, it always defaults to UNKNOWN.


✌🏼 Like my content? Subscribe via RSS feed.