如何使 CompletableFuture 异常函数返回 Collection 类型?

问题描述 投票:0回答:0

我从事的项目有一些代码可以简化为以下两个功能:

  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,顺便说一句。

java generics completable-future
© www.soinside.com 2019 - 2024. All rights reserved.