Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 754 Vote(s) - 3.54 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to define a non-ordinal enum in Kotlin?

#1
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**.
Reply

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

<!-- language: kotlin -->

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:

<!-- language: kotlin -->

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.

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through