Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an enum from an Int in Kotlin?

Tags:

enums

kotlin

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

like image 479
pableiros Avatar asked Nov 28 '18 16:11

pableiros


People also ask

How do I get enum from int Kotlin?

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.

Can we use integer in enum?

No, we can have only strings as elements in an enumeration.


1 Answers

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.

like image 124
Francesc Avatar answered Oct 08 '22 08:10

Francesc