I have a method of kotlin like below
fun initDrawer(drawerView: DrawerView, drawerLayout: DrawerLayout, context: Context, onRefreshClick: () -> Unit) {
}
But when I try to pass initDrawer(drawerView,drawerlayout,this,onRefreshClick()) it gives me an error of required () cannot be applied to(kotlin.Unit)
is it possible to pass methods from java to kotlin.
Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.
You can call Kotlin functions in Java as well as Java methods and variables in Kotlin code.
In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas. Frequently, lambdas are passed as parameter in Kotlin functions for the convenience.
If your question is can you use kotlin files in java files and vice versa then the answer is yes.
You have to set return value of your onRefreshClick to Unit:
private Unit onRefreshClick() {
//do something here
return Unit.INSTANCE;
}
Then you can call it like this:
initDrawer(drawerView, drawerLayout, this, this::onRefreshClick);
You cannot pass your Java method directly from Java, as the Kotlin parameter expects the method to return Unit
.
You can follow the following pattern:
kotlinClass.higherOrderFunction(() -> {functionToPass(); return Unit.INSTANCE;});
where functionToPass()
is defined as:
private void functionToPass() {
// do something
}
In your case:
initDrawer(drawerView, drawerlayout, this,
() -> {onRefreshClick(); return Unit.INSTANCE;})
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