user5507535
user5507535

Reputation: 1800

Is it possible to have the enum ordinal in kotlin without explicitly calling ordinal?

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

Answers (2)

BAZTED
BAZTED

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

jrtapsell
jrtapsell

Reputation: 7021

Overriding operators

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:

  • unaryPlus
    • This overrides the + operator, which I use as +day
  • not
    • This overrides the ! operator, which I use as !day

Using extension functions

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:

  • Using code
    • Extension function (Enum member)
      • Target method (Ordinal)

Upvotes: 3

Related Questions