Java说我要返回一个类型,但我认为我要返回第6行的那个类型。
5号线上:
The method thenApply(Function<? super Integer,? extends U>) in the type CompletableFuture<Integer> is not applicable for the
arguments ((<no type> response) -> {})
如果我取消对第6行的注释,它就会编译,但这是因为返回了一个nullCompletableFuture。换句话说,类型HttpResponse已从CompletableFuture泛型类中删除。
这是我尝试做的事情的一个简化片段,即在Java 11应用程序中以异步方式实现重试逻辑。我希望thenApply逻辑返回CompletableFuture<HttpResponse>然后我将把它封装到重试逻辑中。
import java.util.concurrent.CompletableFuture;
public class StackOverflow {
public static CompletableFuture<Integer> sendAsync(Integer response) {
return CompletableFuture.completedFuture(response);
}
public static void main(String args[]){
CompletableFuture<Integer> aFuture =
sendAsync(200)
.thenApply(response -> { // Line 5
CompletableFuture<Integer> result = null; // Line 6
if (response >= 200 && response < 300) {
result = CompletableFuture.supplyAsync(() -> {
return response;
});
} else {
throw new RuntimeException();
};
// return null;
});
}
}
谢谢,Woodsman
对于其他患有这种疾病的人:
由于代码写在上面,thenApply没有返回ComplexableFuture,但更确切地说是ComplextableFuture<可完成的未来>。为了使其变平,我将Apply更改为Compose。这产生了一个类型CompleteableFuture。
在消息中:
The method thenApply(Function<? super Integer,? extends U>) in the type CompletableFuture<Integer> is not applicable for the
arguments ((<no type> response) -> {})
参数Function<?超级整数,?扩展U>并不意味着我最初的想法。这个有点像Perl的表达式意味着提供一个Lambda函数,该函数接受一个扩展或是Integer的参数,并且不返回未知或void。相反,U表示返回一个稍微复杂的类型或嵌套类型。
import java.util.concurrent.CompletableFuture;
public class StackOverflow {
public static CompletableFuture<Integer> sendAsync(Integer response) {
return CompletableFuture.completedFuture(response);
}
public static void main(String args[]){
CompletableFuture<Integer> aFuture =
sendAsync(200)
.thenCompose(response -> { // Line 5
CompletableFuture<Integer> result = null; // Line 6
if (response >= 200 && response < 300) {
result = CompletableFuture.supplyAsync(() -> {
return response;
});
} else {
throw new RuntimeException();
};
return result;
});
}
}