It really depends on what you actually want to do.
- If you need a specific hardcoded enum value, then you can directly use
Types.FOO
- If you are receiving the value dynamically from somewhere else in your code, you should try to use the enum type directly in order not to have to perform this kind of conversions
- If you are receiving the value from a webservice, there should be something in your deserialization tool to allow this kind of conversion (like Jackson's
@JsonValue
) - If you want to get the enum value based on one of its properties (like the
value
property here), then I'm afraid you'll have to implement your own conversion method, as @Zoe pointed out.
One way to implement this custom conversion is by adding a companion object with the conversion method:
enum class Types(val value: Int) { FOO(1), BAR(2), FOO_BAR(3); companion object { private val types = values().associate { it.value to it } fun findByValue(value: Int): Types? = types[value] }}
Companion objects in Kotlin are meant to contain members that belong to the class but that are not tied to any instance (like Java's static
members).Implementing the method there allows you to access your value by calling:
var bar = Types.findByValue(2) ?: error("No Types enum value found for 2")
Note that the returned value is nullable, to account for the possibility that no enum value corresponds to the parameter that was passed in. You can use the elvis operator ?:
to handle that case with an error or a default value.