How to pass any (known at runtime only) Kotlin enum as parameter to a method in Java code?

8.5k Views Asked by At

Say we have enums

enum class Status {
    OPEN, CLOSED
}

enum class Weekday {
    WORKDAY, DAYOFF
}

Having a Java class

public KotlinInvoker {
    public methodWithKotlinEnumAsParameter_namely_AppendWorkingStatusString( ? kotlinEnum) {
    ...
    }
}

The Goal is to directely pass ANY jave / kotlin enum to that kind of the function like if Java you would have a

    <E extends java.lang.Enum<E>>
    methodAcceptingEnumAsParameter(E enum) {
    ...
    return result + ' ' + enum.toString();
    }

so you can pass ANY enum to it. what should be the method signature to play nicely with kotlin enum as well as it is mapped to java enum accordingly to official kotlin docs?

1

There are 1 best solutions below

1
On

Your Java example works in Kotlin just fine:

enum class Status {
    OPEN, CLOSED
}

enum class Weekday {
    WORKDAY, DAYOFF
}

fun <E : Enum<E>> methodWithKotlinEnumAsParameter(arg : E)
{
    println(arg.name)
}

Now, if you for example call methodWithKotlinEnumAsParameter(Weekday.DAYOFF), it will print DAYOFF to the console.