简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM