SoBeRich
SoBeRich

Reputation: 802

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

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?

Upvotes: 7

Views: 9449

Answers (1)

msrd0
msrd0

Reputation: 8361

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.

Upvotes: 10

Related Questions