9

In the official document, I found enumValues() function.

I used enumValues() function, but I cannot find difference.

enum class RGB {
    RED, GREEN, BLUE
}

RGB.values().joinToString { it.name } // RED, GREEN, BLUE
enumValues<RGB>().joinToString { it.name } // RED, GREEN, BLUE

What difference between enumValues() and Enum.values()?

Is it a function for platforms other than JVM? Or are there other use cases?

1
  • 2
    In the same documentation you mentioned it's specified that since Kotlin 1.1, it's possible to access the constants in an enum class in a generic way, using the enumValues<T>() and enumValueOf<T>() functions. EnumClass.values() is still used and has the same operational meaning, read above the enumValues(). Commented Mar 5, 2019 at 8:23

1 Answer 1

17

The problem with values() is that it only exists on each concrete enum class, and you can't call it on a generic enum to get its values, which is quite useful in some cases. Taking just the simplest example of wanting to access all values in a String, enumValues lets you write a function like this:

inline fun <reified T: Enum<T>> getEnumValuesString(): String {
    // could call RGB.values(), but not T.values()
    // even with the generic constraint and reified generics

    // this works, however
    return enumValues<T>().joinToString()
}

Which can then be called with any enum class you've defined:

getEnumValuesString<RGB>()
Sign up to request clarification or add additional context in comments.

1 Comment

But how does this work, compiler magic? Since the values array is physically on the concrete enum, isnt it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.