Amazing Kotlin Enum Entries property example

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"),
}

source

you can define functions like

@OptIn(ExperimentalStdlibApi::class)
val dancersLastNames = Dancer.entries.associateBy { it.lastName }.keys

source

@OptIn(ExperimentalStdlibApi::class)
val dancersFirstNames = Dancer.entries.associateBy { it.firstName }.keys

source

Calling these functions with

fun main() {
    println(dancersFirstNames)
    println(dancersLastNames)
}

source

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

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,
            )
    }

source 1,2

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.