在C枚举中,所有数字都是数字,您只能通过名称引用该值。
示例:
#include <stdio.h>
enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday };
int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}
输出:第4天
在Kotlin我想要类似的东西,至少能够摆脱.ordinal
。
目前它是这样的:
enum class Week { sunday, monday, tuesday, wednesday, thursday, friday, saturday }
要访问元素,我必须使用详细Week.monday.ordinal
答案 0 :(得分:3)
演示代码:
enum class WeekDay {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
companion object: Iterable<WeekDay> {
override fun iterator() = values().iterator()
}
operator fun unaryPlus() = ordinal
operator fun not() = ordinal
}
fun main(args: Array<String>) {
for (day in WeekDay) {
println("$day ${!day} ${+day}")
}
}
输出:
MONDAY 0 0
TUESDAY 1 1
WEDNESDAY 2 2
THURSDAY 3 3
FRIDAY 4 4
SATURDAY 5 5
SUNDAY 6 6
这显示了如何使用一元运算符来获取序数,我已经包含了两个例子:
+day
!day
您可以创建一个调用您要调用的函数的扩展函数,但从传递的值中获取序数。这将使这样的调用:
答案 1 :(得分:3)
基本上@jrtapsell的答案非常充实。但是在kotlin中你可以覆盖 invoke()运算符。
enum class Weekday { MONDAY, TUESDAY;
operator fun invoke(): Int {
return ordinal
}
}
fun main(args: Array<String>) {
print("${Weekday.TUESDAY() + 1}")
}
结果:2
AFM它更漂亮。