扩展 CompletableFuture 时类型不匹配
Type mismatch when extending CompletableFuture
我正在尝试扩展 CompletableFuture
以在 handle
之后执行 thenCompose
,但出现编译器错误:
Type mismatch: cannot convert from CompletableFuture(Object) to CompletableFuture(U)
这是我的代码:
public class MyCompletableFuture<T> extends CompletableFuture<T> {
public <U> CompletableFuture<U> handleAndCompose(BiFunction<? super T, Throwable, ? extends U> fn) {
return super.handle(fn).thenCompose(x->x);
}
}
郑重声明,我试图隐藏 上使用的 thenCompose
,基本上是:
.handle((x, t) -> {
if (t != null) {
return askPong("Ping");
} else {
return x;
}
)
您方法的签名不正确。应该是:
public <U> CompletableFuture<U> handleAndCompose(BiFunction<? super T, Throwable, ? extends CompletableFuture<U>> fn) {
return super.handle(fn).thenCompose(x->x);
}
注意函数给出的是returns? extends CompletableFuture<U>
而不是? extends U
。您也可以接受更通用的 CompletionStage
而不是 CompletableFuture
.
作为参数
我正在尝试扩展 CompletableFuture
以在 handle
之后执行 thenCompose
,但出现编译器错误:
Type mismatch: cannot convert from CompletableFuture(Object) to CompletableFuture(U)
这是我的代码:
public class MyCompletableFuture<T> extends CompletableFuture<T> {
public <U> CompletableFuture<U> handleAndCompose(BiFunction<? super T, Throwable, ? extends U> fn) {
return super.handle(fn).thenCompose(x->x);
}
}
郑重声明,我试图隐藏 thenCompose
,基本上是:
.handle((x, t) -> {
if (t != null) {
return askPong("Ping");
} else {
return x;
}
)
您方法的签名不正确。应该是:
public <U> CompletableFuture<U> handleAndCompose(BiFunction<? super T, Throwable, ? extends CompletableFuture<U>> fn) {
return super.handle(fn).thenCompose(x->x);
}
注意函数给出的是returns? extends CompletableFuture<U>
而不是? extends U
。您也可以接受更通用的 CompletionStage
而不是 CompletableFuture
.