Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we pass java method to to kotlin function of type () -> Unit?

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.

like image 870
avez raj Avatar asked Apr 18 '18 10:04

avez raj


People also ask

What does () -> Unit mean in 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.

Can you call Java methods in Kotlin?

You can call Kotlin functions in Java as well as Java methods and variables in Kotlin code.

How do you pass the function in the method Kotlin?

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.

Can Java and Kotlin be used together?

If your question is can you use kotlin files in java files and vice versa then the answer is yes.


2 Answers

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);
like image 162
Dmitry Avatar answered Sep 24 '22 09:09

Dmitry


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;}) 
like image 22
DVarga Avatar answered Sep 23 '22 09:09

DVarga