简体   繁体   English

如何将Kotlin lambda传递给Java Supplier参数?

[英]How to pass Kotlin lambda to Java Supplier argument?

I migrate my project to Kotlin and this phase has a lot of interaction between Java and Kotlin. 我将项目迁移到Kotlin,并且此阶段在Java和Kotlin之间进行了大量交互。

In sample below I need to pass a function which implements Java Supplier interface. 在下面的示例中,我需要传递一个实现Java Supplier接口的函数。

java.util.concurrent.CompletableFuture.supplyAsync<Int>({ -> 3 }, executor)

CompletableFuture.supplyAsync({ 3 }, executor)

IntellJ shows error: IntellJ显示错误:

Type mismatch.
Required: Supplier<Int!>!
Found: () -> Int

I found a workaround with a helper class but it is not an inline solution. 我发现了一个帮助器类的解决方法,但这不是嵌入式解决方案。

class Help : Supplier<Int> { fun get() = 3 }
supplyAsync(Help(), executor)

This will work: 这将起作用:

CompletableFuture.supplyAsync({ 3 }, executor::execute)

Note that the two signatures are 请注意,这两个签名是

public static <U> supplyAsync(supplier: Supplier<U>, executor: Executor): CompletableFuture<U>
public static <U> supplyAsync(supplier: () -> U, executor: (Runnable) -> Unit): CompletableFuture<U>

That is, if you want to pass in a lambda, the thing that executes it has to be a method reference (instead of an Executor instance). 也就是说,如果您要传递lambda,则执行它的对象必须是方法引用(而不是Executor实例)。

Edit: This is documented here , Kotlin allows you to call methods that take SAM (functional interface) parameters with proper Kotlin functions as arguments. 编辑:这里记录此文档,Kotlin允许您调用以SAM(功能接口)参数为参数的方法,并带有适当的Kotlin函数作为参数。 However, this is all or nothing. 但是,这是全部或全部。 Either you pass a Kotlin function for all SAM parameters, or for none. 您可以为所有SAM参数传递Kotlin函数,或者不传递任何参数。 This explains why the approach you originally took didn't compile. 这就解释了为什么您最初采用的方法没有编译。 This is not specific methods of the Java API, but instead works for all methods defined on Java classes. 这不是Java API的特定方法,而是适用于Java类上定义的所有方法。

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

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