有没有更好的方法来写kotlin的CompletableFutrue.XXXasync()调用?

Java CompletableFuture<T>具有很多异步方法,静态或实例,这种格式

 public <U> CompletableFuture<U> XXXasync(SomeFunctionalInterface<T> something, Executor executor) 

如果你对kotlin有足够的FP经验,你会立刻意识到这些函数在kotlin中使用是非常尴尬的,因为SAM接口不是最后一个参数。

 aCompletableFutrue.thenComposeAsync(Function<SomeType, CompletableFuture<SomeOtherType>> { // ^ WHAT A LONG TYPE NAME THAT NEED TO BE HAND WRITTEN // do something that has to be written in multiple lines. // for that sake of simplicity I use convert() to represent this process convert(it) }, executor) 

Function有一个非常长的通用签名,我不知道如何让IDE生成。 如果类型名称变得更长或者包含ParameterizedType或者具有类型差异注释,那么这将是一个简单的例子。

它也看起来令人讨厌,因为第5行的, executor)

在kotlin或IDE中是否有一些缺失的功能可以帮助解决这个问题? 至少我不想自己编写那个长的SAM构造函数。


拒绝解决方案:

  1. 使用命名参数似乎不工作,因为此功能只适用于kotlin函数。

  2. 放弃异步方法从一开始就听起来很糟糕。

  3. Kotlin corountine被拒绝是因为我们正在使用一些仅接受CompletionStage愚蠢的Java库。

如果你最后调用了一个java接口函数接口参数,你可以在kotlin中使用lambda。

 val composed: CompletableFuture<String> = aCompletableFutrue.thenComposeAsync { CompletableFuture.supplyAsync { it.toString() } }; 

其次 ,如果你不喜欢java api方法签名。 您可以编写自己的扩展方法,例如:

 fun <T, U> CompletableFuture<T>.thenComposeAsync(executor: Executor , mapping: Function1<in T, out CompletionStage<U>>): CompletableFuture<U> { return thenComposeAsync(Function<T,CompletionStage<U>>{mapping(it)}, executor) } 

那么你可以沿着方法制作lambda。

 aCompletableFutrue.thenComposeAsync(executor){ // do working }