
With the recent Kotlin 1.8.20 release a
modern and performant replacement of the Enum class values function
https://kotlinlang.org/docs/whatsnew1820.html#a-modern-and-performant-replacement-of-the-enum-class-values-function
has been entroduced.
In a nutshell: a new entries
property that returns a pre-allocated immutable list of defined enum constants.
Suppose you have a enum class definition:
enum class Dancer(val firstName: String, val lastName: String) { SAMBA("Beatriz", "Santos"), WALTZ("Emma", "Steiner"), TANGO("Santino", "Gomez"), }
you can define functions like
@OptIn(ExperimentalStdlibApi::class) val dancersLastNames = Dancer.entries.associateBy { it.lastName }.keys
@OptIn(ExperimentalStdlibApi::class) val dancersFirstNames = Dancer.entries.associateBy { it.firstName }.keys
Calling these functions with
fun main() { println(dancersFirstNames) println(dancersLastNames) }
returns
[Beatriz, Emma, Santino]
[Santos, Steiner, Gomez]
You can achieve the same functionality with values()
function e.g.:
Dancer.values().associateBy { it.lastName }.keys
however you call a function instead of a property and you’d avoid hidden performance issues.
Code
- https://github.com/lotharschulz/kotlin-enum-entries
- https://codeberg.org/lotharschulz/kotlin-enum-entries
Build descriptor changes
In order to run the code above that language-version 1.9
compiler option needs to be enabled:
tasks .withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask<*>>() .configureEach { compilerOptions .languageVersion .set( org.jetbrains.kotlin.gradle.dsl.KotlinVersion.KOTLIN_1_9, ) }
Leave a Reply