How to define a non-ordinal enum in Kotlin?

51,552

You should define value as property (val) not as constructor parameter. After that it becomes accessible:

enum class States(val value: Int) {
    STATE_A(1),
    STATE_B(2),
    STATE_C(3),
    STATE_D(4)
}
...
println(States.STATE_C.value) // prints 3

Also consider to use ordinal, which may be suitable in your case:

enum class States {
    STATE_A,
    STATE_B,
    STATE_C,
    STATE_D
}
...
println(States.STATE_C.ordinal + 1) // prints 3

If you go with that approach, be careful - any change of States order can break your code.

Share:
51,552

Related videos on Youtube

Hamed
Author by

Hamed

Mobile developer with over 9 years of IT experience in analysis, design, and development of various native and multi-platform mobile applications.

Updated on September 05, 2020

Comments

  • Hamed
    Hamed over 3 years

    I want to define an enum that values are not ordinal, for example:

    enum class States(value: Int) {
        STATE_A(4),
        STATE_B(5),
        STATE_C(7),
        STATE_D(12)
    }
    

    How can I get the value of each item? For instance States.STATE_C should return 7.

  • Armando Marques da S Sobrinho
    Armando Marques da S Sobrinho over 4 years
    Hi @hluhovskyi, so, technically would the ordinal index will be based on 1?
  • enreas
    enreas almost 4 years