https://kotlinlang.org logo
Title
k

KotlinLeaner

05/05/2023, 8:44 AM
Hi guys, I have a enum class and I want to find the enum.
enum class Stage(val title: String) {
    ONE("one"),
    TWO("two");

    companion object {
        // 1st option
        fun fromTitle(title: String)  {
            values().firstOrNull { it.title.equals(title, true) }
        }

        // 2nd option
        private val mapByTitle = Stage.values().associateBy(Stage::title)
        fun fromTitle(title: String) = mapByTitle[title.lowercase()]
    }
}
which one is better in options?
k

Klitos Kyriacou

05/05/2023, 10:54 AM
It depends on whether
Stage.fromTitle
is going to be called frequently enough that performance is an important consideration. If not, then option 1 will be sufficient. The call to
values()
creates a new array every single time it's called, but if performance is not a concern, it doesn't matter. In Kotlin 1.9, this issue will go away - see https://youtrack.jetbrains.com/issue/KT-48872. You will then be able to do it this way:
fun fromTitle(title: String) = entries.firstOrNull { it.title.equals(title, true) }
without worrying about creating a new array each time. Using a
Map
is not going to bring much (if any) performance benefit over iterating for the typically small number of entries in an enum.
k

KotlinLeaner

05/05/2023, 11:08 AM
Perfect thanks
j

Jan

05/05/2023, 7:34 PM
You could also use the valueOf(title.uppercase) method if your title is the same as the enum name