我从事的项目有一些代码可以简化为以下两个功能:
CompletionStage<Collection<String>> fn1(String prefix) {
return fn2()
.thenApply(list -> list.stream()
.map(s -> prefix + s)
.collect(Collectors.toList())
);
}
CompletionStage<List<String>> fn2() {
return CompletableFuture.completedFuture(List.of("results", "of", "computation"));
}
效果很好。但是,
fn1
在添加exceptionally
步骤后无法编译:
CompletionStage<Collection<String>> fn1(String prefix) {
return fn2()
.thenApply(list -> list.stream()
.map(s -> prefix + s)
.collect(Collectors.toList())
).exceptionally(t -> {
// Log the error
// ...
// return an empty collection
Collection<String> emptyCol = List.of();
return emptyCol; // Error: Collection<String> cannot be converted to List<String>
// List<String> emptyList = List.of();
// return emptyList; // Error: CompletionStage<List<String>> cannot be converted to CompletionStage<Collection<String>>
// return emptyList.stream().collect(Collectors.toList()); // Error same as above
});
}
假设我们无法更改
fn1
的签名,如何解决?为什么.collect(Collectors.toList())
适合thenApply
?
JDK 是 11,顺便说一句。