[英]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);
我不明白我的代码有什么问题以及为什么它无法编译。
您需要使用toCompletableFuture
将CompletionStage
转换为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.