Reputation: 1800
In C enums are all numeric and you can reference the value just by the name.
Example:
#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;
}
Outputs: day 4
In Kotlin I would like something similar, at least being able to get rid of the .ordinal
.
Currently it's like this:
enum class Week { sunday, monday, tuesday, wednesday, thursday, friday, saturday }
and to access an element I have to use the verbose Week.monday.ordinal
Upvotes: 5
Views: 1725
Reputation: 546
Basically answer by @jrtapsell is great and full. But also in kotlin you can override invoke() operator.
enum class Weekday { MONDAY, TUESDAY;
operator fun invoke(): Int {
return ordinal
}
}
fun main(args: Array<String>) {
print("${Weekday.TUESDAY() + 1}")
}
Result: 2
AFM it is much prettier.
Upvotes: 5
Reputation: 7021
Demo code:
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}")
}
}
Output:
MONDAY 0 0
TUESDAY 1 1
WEDNESDAY 2 2
THURSDAY 3 3
FRIDAY 4 4
SATURDAY 5 5
SUNDAY 6 6
This shows how to use unary operators to get the ordinals, I have included 2 examples:
+day
!day
You can create an extension function which calls the function you want to call, but gets the ordinal from the passed value. This would make the call like this:
Upvotes: 3