Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

kotlin

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

like image 957
user5507535 Avatar asked Jan 28 '23 07:01

user5507535


1 Answers

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.

like image 182
BAZTED Avatar answered Jan 31 '23 09:01

BAZTED