Reputation: 1855
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?
Upvotes: 9
Views: 3605
Reputation: 89578
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>()
Upvotes: 17