简体   繁体   English

如何将 lambda 从 Java 传递给 Kotlin 方法?

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

Can I call this Kotlin method from Java?我可以从 Java 调用这个 Kotlin 方法吗?

fun foo(() -> Unit)

If so, what's the syntax?如果是这样,语法是什么?

You need to create instance of Function0 :您需要创建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或者如果您使用 Java 8,则可以简化

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 .如果您的 Kotlin 函数返回一个Unit ,Java 将需要返回Unitnull ,因为voidUnit不太一样。

My example that worked:我的例子有效:

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

Or, if you want to be really explicit about Unit ...或者,如果您想真正明确地了解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您需要查看生成的 Kotlin Bytecode -> 反编译它

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现在你知道为了从 Java 中调用这个函数,你需要像这样创建 Function0 的实例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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