Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Enum.values() and enumValues() in kotlin

Tags:

enums

kotlin

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?

like image 469
galcyurio Avatar asked Mar 05 '19 08:03

galcyurio


People also ask

What's the difference between enum and sealed class?

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.

What is the use of enum in Kotlin?

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.

How do I get the enum value in Kotlin?

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.

Can enum implement an interface 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.


1 Answers

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>()
like image 109
zsmb13 Avatar answered Sep 23 '22 10:09

zsmb13