Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 644
SoBeRich Avatar asked May 31 '18 15:05

SoBeRich


People also ask

How to initialize an enum class in Kotlin?

Since enum constants are instances of an Enum class, the constants can be initialized by passing specific values to the primary constructor. As in Java and in other programming languages, Kotlin enum classes has some inbuilt properties and functions which can be used by the programmer. Here’s a look at the major properties and methods.

How to use member function as parameter in Kotlin class?

About the member function as parameter: Kotlin class doesn't support static member function, so the member function can't be invoked like: Operator::add(5, 4) Therefore, the member function can't be used as same as the First-class function. A useful approach is to wrap the function with a lambda.

Does Kotlin support Java interfaces?

This support for Java means that Kotlin function literals can be automatically converted into implementations of Java interfaces with a single non-default method, as long as the parameter types of the interface method match the parameter types of the Kotlin function. You can use this for creating instances of SAM interfaces:

Is it possible to pass an array to a Kotlin method?

Passing an array of a subclass as an array of superclass to a Kotlin method is also prohibited, but for Java methods this is allowed through platform types of the form Array< (out) String>!. Arrays are used with primitive datatypes on the Java platform to avoid the cost of boxing/unboxing operations.


1 Answers

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.

like image 69
msrd0 Avatar answered Sep 29 '22 21:09

msrd0