How to call Kotlin function with function as parameter in Java Code?

Viewed 1900

I have a kotlin method as follows:

fun methodWithCallBackAsParameter(callback:() -> Unit) {
    //Do Somejob
    callback()
}

In kotlin we simply use this method with following syntax:

methodWithCallBackAsParameter {
    //Some Instructions here.
}

Now I want to use this Kotlin method in a Java class but I am not able to figure out how.

5 Answers

Just return Unit.INSTANCE in the end of the lambda expression.

if you want to use lambda in android you have to change your app to use Java 1.8 instead of 1.7 use can do that by it from gradle

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

for more look this documentation https://developer.android.com/studio/write/java8-support

I believe you want to do this.

    public class Program {

    public static void main(String[] args) {
        FunctionKt.methodWithCallBackAsParameter(() -> {
            System.out.printf("do something");
            return null;
        });
    }
}

In this example, the function methodWithCallBackAsParameter was defined in the function.kt file.

You can do something like this:

Supposing the kotlin method is

fun handleResult(
    data: Intent?,
    callbackSuccess: (String) -> Unit,
    callbackError: (String) -> Unit
)

Then when you call this from Java you call it like this (either by matching the signature or doing some logic inside)

    handleResult(data, this::success, this::failure);

    handleResult(data, (statusCode) -> success(statusCode), (errorMessage) -> failure(errorMessage));


    private Unit failure(String errorMessage) {
        // do something java here
        return Unit.INSTANCE;
    }

    private Unit success(String code) {
        // do something java here
        return Unit.INSTANCE;
    }

When use in Java: callback: () -> Unit = new Function0<>()

Related