I have this enum
:
enum class Types(val value: Int) { FOO(1) BAR(2) FOO_BAR(3) }
How do I create an instance of that enum
using an Int
?
I tried doing something like this:
val type = Types.valueOf(1)
And I get the error:
Integer literal does not conform to the expected type String
If you want to grab one based on an int value, you need to define your own function to do so. You can get the values in an enum using values() , which returns an Array<Types> in this case. You can use firstOrNull as a safe approach, or first if you prefer an exception over null.
No, we can have only strings as elements in an enumeration.
enum class Types(val value: Int) { FOO(1), BAR(2), FOO_BAR(3); companion object { fun fromInt(value: Int) = Types.values().first { it.value == value } } }
You may want to add a safety check for the range and return null.
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