23

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.

1

3 Answers 3

41

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);
1
  • () -> Unit is a function (lambda) that returns Unit. Unit onRefreshClick() { } is what you need.
    – Dmitry
    Apr 18, 2018 at 11:17
8

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;}) 
1

Let's say your Java method resides in a class called Test:

public class Test {
    void onRefreshClick() {
        System.out.println("test");
    }
}

It could be called by your Kotlin function like this (as reference):

val t = Test()
initDrawer(drawerView, drawerlayout, this, t::onRefreshClick)

onRefreshClick could also be static in Java which would enable you to use it like this:

initDrawer(drawerView, drawerlayout, this, Test::onRefreshClick)

Note: In Kotlin () -> Unit is the type of a function which has no arguments and returns nothing (which is Unit and not Nothing as return type).

There is no Unit in Java. The Java method which corresponds to this type would have no arguments and as return type void.

1
  • onRefreshClick() is java method
    – avez raj
    Apr 18, 2018 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.