4

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.

Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63

5 Answers5

5

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

nyarian
  • 4,085
  • 1
  • 19
  • 51
  • I tried returning Unit.INSTANCE; it now says, Lambda expressions are not supported at language level 7. – Prajeet Shrestha Nov 16 '18 at 13:19
  • Either set language level to 1.8 or transform the lambda into anonymous class. This error occurred because lambdas are supported from Java 1.8, and your project uses Java 1.7. – nyarian Nov 16 '18 at 13:21
1

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

gmetax
  • 3,853
  • 2
  • 31
  • 45
0

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
0

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;
    }
Catalin
  • 1,821
  • 4
  • 26
  • 32
-1

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

blackgreen
  • 34,072
  • 23
  • 111
  • 129
pan he
  • 64
  • 7