KotlinLeaner
05/05/2023, 8:44 AMenum 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?Klitos Kyriacou
05/05/2023, 10:54 AMStage.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.KotlinLeaner
05/05/2023, 11:08 AMJan
05/05/2023, 7:34 PM