有没有更好的方法在 kotlin 中编写 CompletableFutrue.XXXasync() 调用?
Is there a better way to write CompletableFutrue.XXXasync() invocations in kotlin?
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构造器。
被拒绝的解决方案:
使用命名参数似乎不起作用,因为此功能仅适用于 kotlin 函数。
放弃异步方法从一开始就听起来很糟糕。
Kotlin 协程被拒绝,因为我们正在使用一些只接受 CompletionStage
的愚蠢 Java 库。
IF 你从 java 调用了 api 最后接受一个功能接口参数,你可以在 kotlin 中使用 lambda。
val composed: CompletableFuture<String> = aCompletableFutrue.thenComposeAsync {
CompletableFuture.supplyAsync { it.toString() }
};
其次,如果你不喜欢javaapi方法签名。您可以编写自己的扩展方法,例如:
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)
}
THEN 你可以按照这个方法制作 lambda。
aCompletableFutrue.thenComposeAsync(executor){
// do working
}
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构造器。
被拒绝的解决方案:
使用命名参数似乎不起作用,因为此功能仅适用于 kotlin 函数。
放弃异步方法从一开始就听起来很糟糕。
Kotlin 协程被拒绝,因为我们正在使用一些只接受
CompletionStage
的愚蠢 Java 库。
IF 你从 java 调用了 api 最后接受一个功能接口参数,你可以在 kotlin 中使用 lambda。
val composed: CompletableFuture<String> = aCompletableFutrue.thenComposeAsync {
CompletableFuture.supplyAsync { it.toString() }
};
其次,如果你不喜欢javaapi方法签名。您可以编写自己的扩展方法,例如:
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)
}
THEN 你可以按照这个方法制作 lambda。
aCompletableFutrue.thenComposeAsync(executor){
// do working
}