https://kotlinlang.org logo
Title
r

Ruckus

06/12/2017, 3:03 PM
You can use something like
enum class People(value: Int) {
    man(1),
    baby(2),
    woman(3);

    companion object {
        fun byValue(value: Int) = values().firstOrNull { it.value == value }
    }
}

val people = People.byValue(3)
if (people != null) {
    print("converted successfully => $people")
} else {
    print("null value -> No Match")
}
If you want it to be more effective (since the
values()
call can be expensive), you can use a map
enum class People(value: Int) {
    man(1),
    baby(2),
    woman(3);

    companion object {
        private val map = values().associateBy(People::value)
        fun byValue(value: Int) = map[value]
    }
}
n

nawar

06/12/2017, 3:13 PM
Awesome! I’ll try it out.