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?
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.
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.
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With