For Enum definition : Is there a way to specify th...
# announcements
t
For Enum definition : Is there a way to specify the ordinal value of the types? Or do you just get what the compiler decides?
n
I think the latter. For some of my projects I have a helper class which then allows to use
Copy code
enum class FieldType(override val value: Int) : SingleValueEnum {
    INVALID(-1),
    TEXTBOX(1),
    DROPDOWN(3);

companion object : SingleValueEnumCompanion<FieldType>(values(), INVALID)
}
The helper code is pretty simple:
Copy code
interface SingleValueEnum {
    val value: Any
}

open class SingleValueEnumCompanion<T : SingleValueEnum>(elements: Array<T>, val invalid: T? = null) {

    private val values = elements.associateBy { it.value }

    private val names = elements.associateBy { it.toString() }

    fun fromValue(value: Any) = values[value] ?: invalid ?: throw IllegalArgumentException("$value is invalid")

    fun fromName(name: String) = names[name] ?: invalid ?: throw IllegalArgumentException("$name is invalid")
}
s
It is in the order of the declaration (left to right, top to bottom) of its values. If you want a unique (integer) custom id, add an integer property.
t
yeah... bummer. ok.
t
So yes, you can define the ordinal - or to be more specific: you can't not define it. It is befinde by the order in which you define the enum constants. Of course you can define any other identifier you want, but the ordinal will always represent the declaration order.