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?
Enum classes represent a concrete set of values, while sealed classes represent a concrete set of classes. Since those classes can be object declarations, we can use sealed classes to a certain degree instead of enums, but not the other way around.
Kotlin enums are classes, which means that they can have one or more constructors. Thus, you can initialize enum constants by passing the values required to one of the valid constructors. This is possible because enum constants are nothing other than instances of the enum class itself.
To get an enum constant by its string value, you can use the function valueOf() on the Enum class. It helps us to get enum from a String value in Kotlin.
In Kotlin, you can also have enums implement interfaces. In such cases, each data value of enum would need to provide an implementation of all the abstract members of the interface. While calling these interface methods, we can directly use the enum value and call the method.
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>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With