Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

In kotlin enum default starting order is 0, how can i change it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...