简体   繁体   中英

How do I pass a lambda from Java to a Kotlin method?

Can I call this Kotlin method from Java?

fun foo(() -> Unit)

If so, what's the syntax?

You need to create instance of Function0 :

foo(new Function0<Unit>() {
    @Override
    public Unit invoke() {
        // Here should be a code you need
        return null;
    }
});

or if you use Java 8 it can be simplified

foo(() -> {
    // Here should be a code you need
    return null;
});

You can call this but need to be careful of the return types. If your Kotlin function returns a Unit , Java will either need to return Unit or null , because void is not quite the same as Unit .

My example that worked:

foo(() -> {
    System.out.println("Hi");
    return null;
});

Or, if you want to be really explicit about Unit ...

foo(() -> {
    System.out.println("Hi");
    return Unit.INSTANCE;
});

I totally agree with Andrew's Answer, There is a better way to approach

  1. You need to see generated Kotlin Bytecode -> Decompile it

In your case it looks something like this:

   public static final void foo(@NotNull Function0 acceptLambda) {
      Intrinsics.checkNotNullParameter(acceptLambda, "acceptLambda");
   }

now you know in order to call this function form Java you need to create instance of Function0 something like this

foo(new Function0<Unit>() {
    @Override
    public Unit invoke() {
        // Your Code
        return null;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM