Kotlin中能否无需显式调用ordinal获取枚举序号?
.ordinal) Great question! In C, enums are essentially numeric values that you can reference directly by name, but Kotlin enums are objects—so you normally need to use .ordinal to get their underlying integer position. Here are a few clean ways to replicate the C-style behavior you want:
1. Overload the plus Operator (Match Your C Example Exactly)
If you want to be able to do things like today + 1 just like in your C code, you can overload the plus operator directly in the enum class. This lets you use the enum instance in arithmetic operations without explicitly calling .ordinal:
enum class Week { sunday, monday, tuesday, wednesday, thursday, friday, saturday; // Overload the plus operator to work with integers operator fun plus(offset: Int): Int { return ordinal + offset } } fun main() { val today = Week.wednesday println("Day ${today + 1}") // Outputs: Day 4 }
This works exactly like your C example—no .ordinal required!
2. Add a Custom value Property
If you want to access the numeric value directly (without arithmetic), adding a value property makes the code more readable than .ordinal, and you can adjust it to match your desired numbering (e.g., start at 1 instead of 0 if needed):
enum class Week { sunday, monday, tuesday, wednesday, thursday, friday, saturday; // Use ordinal directly, or ordinal +1 to start numbering at 1 val value get() = ordinal } fun main() { val today = Week.wednesday println("Day ${today.value + 1}") // Outputs: Day 4 // Or if you set value to ordinal +1: println("Day ${today.value}") }
3. Define a toInt() Function
Another option is to add a toInt() function to convert the enum to its numeric equivalent, which feels natural if you're used to type conversion:
enum class Week { sunday, monday, tuesday, wednesday, thursday, friday, saturday; fun toInt() = ordinal } fun main() { val today = Week.wednesday println("Day ${today.toInt() + 1}") // Outputs: Day 4 }
Bonus: Custom Numbering (If You Don't Want to Use Ordinal)
If you ever need custom numeric values (not just the default ordinal position), you can define them explicitly in the enum entries. This gives you full control over the numbers, which is useful if your enum doesn't follow a simple 0-based sequence:
enum class Week(val value: Int) { sunday(0), monday(1), tuesday(2), wednesday(3), thursday(4), friday(5), saturday(6); operator fun plus(offset: Int): Int { return value + offset } } fun main() { val today = Week.wednesday println("Day ${today +1}") // Still outputs Day 4 }
All these approaches let you avoid typing .ordinal every time, making your Kotlin code feel more like the C enum behavior you're familiar with.
内容的提问来源于stack exchange,提问作者user5507535

