chancyWu
chancyWu

Reputation: 14393

iterate enum internal values in kotlin

I know there was a similar question . For me, the enum is as below:

enum class Gender (val s:String) {
    Female("female"),
    Male("male")
}

How can i iterate the Gender enum and get "female" or "male"?

Upvotes: 1

Views: 2575

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170745

Android-specific, since it's mentioned in your tags: Proguard can't optimize this case (or at least it couldn't in 2018), so it may be better to do:

enum class Gender {
    Female,
    Male
}

val Gender.s get() = when(this) {
    Female -> "female"
    Male -> "male"
}

Then use @Slaw's comment or @Asgeir's answer, they will work as with your initial code.

Upvotes: 0

Akshay Raiyani
Akshay Raiyani

Reputation: 1333

Use the latest version of enum

@StringDef(Female, Male)
@Retention(AnnotationRetention.SOURCE)
annotation class Gender {
    companion object {
        const val Female = "female"
        const val Male = "male"
    }
}

For More information

Upvotes: 0

Asgeir
Asgeir

Reputation: 41

Here is a simple example. There are a few ways to iterate the values but they are the same as iterating any Array.

fun main() {
    for (gender in Gender.values()) {
        println(gender.s)
    }
}

enum class Gender(val s: String) {
    Female("female"),
    Male("male")
}

For the keen eye, the 's' variable created in the Gender class declaration will also become the variable to access when iterating the Gender values. The confusing bit here is that you think of 'Female' as the key and 'female' as the value of that key. Enums however list each type within itself as values.

Upvotes: 4

Related Questions