Hello, World! I have a pattern that happens a lot...
# announcements
b
Hello, World! I have a pattern that happens a lot in our codebase: enums with a String key, and we need to get the enum value from the key, or a special “unknown” value. So what we do currently is something like:
Copy code
enum class MyEnum(val key: String) {
    FOO("foo"),
    BAR("bar"),
    UNKNOWN("unknown");

    companion object {
        fun getByKey(key: String?): MyEnum {
            return MyEnum.values().firstOrNull { it.key == key } ?: MyEnum.UNKNOWN
        }
    }
}
I’m looking for a way to not repeat this companion object for all our enums. Possibly a combination of an interface and a generic extension function? Any idea? 🙂 [sorry I already posted this before to an unrelated channel by mistake]
o
Have you considered nullable enums?
b
unfortunately in our case
null
and
UNKNOWN
mean different things
m
Here a possible solution that I posted in the other channel:
Copy code
interface EnumCompanion<T, K> {
    fun T.key(): K
    val default: T
}

inline fun <reified T : Enum<T>, R> EnumCompanion<T, R>.getByKey(key: R): T {
    return enumValues<T>().find { it.key() == key } ?: default
}

enum class MyEnum(val key: String) {
    FOO("foo"),
    BAR("bar"),
    UNKNOWN("unknown");

    companion object : EnumCompanion<MyEnum, String> {
        override fun MyEnum.key() = key
        override val default = UNKNOWN
    }
}
👍 1
b
I was gonna mention this 🙂 Sorry about the wrong #channel mishap