0

enum class CoffeeStrength { LEVEL1, LEVEL2, LEVEL3, LEVEL4, LEVEL5 }

DARAKA
  • 13
  • 1
  • You don't change it. What problem are you actually trying to solve? – Slaw Jan 24 '21 at 02:24
  • i want level1 = 1 ... level5 = 5 in c# enum working like that you can change sarting value i cant change it in kotlin? – DARAKA Jan 24 '21 at 02:28
  • You can't change the ordinal, as far as I know. But you can add your own property and/or function to the enum. Or create an extension function. – Slaw Jan 24 '21 at 02:31
  • Note that enums in C# [appear to be different](https://stackoverflow.com/questions/469287/c-sharp-vs-java-enum-for-those-new-to-c) than in Java/Kotlin. – Slaw Jan 24 '21 at 02:39

1 Answers1

3

Kotlin enums have an ordinal property that starts at zero and cannot be modified. If you want some other numbering system, you can create a property for it like this:

enum class CoffeeStrength {
    LEVEL1, LEVEL2, LEVEL3, LEVEL4, LEVEL5;

    val level: Int
        get() = ordinal + 1
}

However, it is typically discouraged to base characteristics off ordinals, because it makes it impossible to insert values or deprecate values without changing the numbering. There are exceptions however. If you have an enum for GregorianMonth, you know the order and count will never change, so it might be fine to use an ordinal.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154