Enum.valueOf in Kotlin

Is there a way to do something like this in Kotlin without reflection?

inline fun <reified T : kotlin.Enum<T>> safeValueOf(type: String?): T? { return java.lang.Enum.valueOf(T::class.java, type) } 

The following example does not compile due to:

Enter the parameter parameter for T in inline fun <reified T : kotlin.Enum<T>> safeValueOf(type: kotlin.String?): T? fails: deduced type TestEnum? not a subtype of kotlin.Enum<TestEnum?>

 enum class TestEnum fun main() { val value: TestEnum? = safeValueOf("test") } 
+5
source share
2 answers

Your function works if you explicitly specify a parameter type value:

 val value = safeValueOf<TestEnum>("test") 

It is assumed that the source code will work, but does not work due to an error in the implementation of type output: https://youtrack.jetbrains.com/issue/KT-11218

+6
source

Starting with Kotlin 1.1, you can access constants in the enum class in a general way, using the functions enumValues ​​() and enumValueOf ():

 enum class RGB { RED, GREEN, BLUE } inline fun <reified T : Enum<T>> printAllValues() { print(enumValues<T>().joinToString { it.name }) } printAllValues<RGB>() // prints RED, GREEN, BLUE 

https://kotlinlang.org/docs/reference/enum-classes.html#working-with-enum-constants

0
source

Source: https://habr.com/ru/post/1243998/


All Articles