簡體   English   中英

此錯誤是什么意思,我的代碼有什么問題?

[英]What does this error mean and what is wrong with my code?

我有以下功能:

  public CompletableFuture<List<String>> getUsers(final String users) {
    final CompletionStage<List<String>> cacheFuture = cache.read(users.toString());

    return cacheFuture.thenCompose((List<String> userList) -> {
      if (userList != null) {
        return CompletableFuture.completedFuture(userList);
      }
      return service.getUsers(users).thenApply((List<String> usersFresh) -> {
          cache.write(users.toString(), usersFresh);
          return usersFresh;
      });
    });
  }

我得到的編譯器錯誤是:

Lambda表達式中的返回類型錯誤:列表無法轉換為U

在線return usersFresh

service.getUsers的方法簽名為:

CompletableFuture<List<String>> getUsers(String users);

我不明白我的代碼有什么問題以及為什么它無法編譯。

您需要使用toCompletableFutureCompletionStage轉換為CompletableFuture ,例如:

  public CompletableFuture<List<String>> getUsers(final String users) {
    final CompletionStage<List<String>> cacheFuture = cache.read(users.toString());


    return cacheFuture.thenCompose((List<String> userList) -> {
      if (userList != null) {
        return CompletableFuture.completedFuture(userList);
      }
      return service.getUsers(users).thenApply((List<String> usersFresh) -> {
          cache.write(users.toString(), usersFresh);
          return usersFresh;
      });
    }).toCompletableFuture();  //!!! convert `CompletionStage` to `CompletableFuture` in here
  }

它與您要返回ArrayList方法類似,但是在方法中返回List

讓我們來看看:

CompletableFuture<T> implements CompletionStage

您的期望回報:

public CompletableFuture<List<String>> 

但是cacheFuture.thenCompose返回CompletionStage

您應該更改:

public CompletableFuture<List<String>> to public CompletionStage<List<String>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM