为了账号安全,请及时绑定邮箱和手机立即绑定

当需要 Completable<Void> 时返回 Completable<Object>

当需要 Completable<Void> 时返回 Completable<Object>

拉丁的传说 2023-08-16 16:37:19
我有以下人员类别:class Person {    String name;    String city;    public void setInfo(PersonInformation info) {//...};}我有一个来自此类的对象列表,我想使用返回 CompletableFuture 的方法异步查询列表中每个项目的数据库来填充它们的信息:List<CompletableFuture<Void>> populateInformation(List<Person> people) {     return people.stream().            .collect(groupingBy(p -> p.getLocation(), toList()))            .entrySet().stream()            .map(entry ->                     CompletableFuture.supplyAsync(                            () -> db.getPeopleInformation(entry.getKey())                    ).thenApply(infoList -> {                                     //do something with info list that doens't return anything                                    // apparently we HAVE to return null, as callanbles have to return a value                                    return null;                                }                    )            ).collect(Collectors.toList());}问题是我收到编译错误,因为方法中的代码返回CompletableFuture<List<Object>>而不是CompletableFuture<List<Void>>. 我在这里做错了什么?我想过删除return null,但正如我在评论中提到的,似乎在可调用中我们必须返回一个值,否则会出现另一个编译错误:Incompatible types: expected not void but the lambda body is a block that is not value-compatible
查看完整描述

2 回答

?
萧十郎

TA贡献1815条经验 获得超12个赞

thenApply方法返回类型为CompletableFuture<U>,这意味着返回 CompletableFuture 并带有函数返回值

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)

返回一个新CompletionStage值,当此阶段正常完成时,将使用此阶段的结果作为所提供函数的参数来执行该新值。有关异常完成的规则,请参阅 CompletionStage 文档。

Type Parameters:
U - the function's return type

Parameters:
fn - the function to use to compute the value of the returned CompletionStage

使用thenAccept方法返回 Void 类型的 CompletableFuture

public CompletableFuture<Void> thenAccept(Consumer<? super T> action)

返回一个新的 CompletionStage,当该阶段正常完成时,将使用该阶段的结果作为所提供操作的参数来执行该阶段。有关异常完成的规则,请参阅 CompletionStage 文档。

Parameters:
action - the action to perform before completing the returned CompletionStage


查看完整回答
反对 回复 2023-08-16
?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

您也可以通过两种方式强制thenApply返回 a :CompletableFuture<Void>

  • 指定泛型类型参数:

    ).<Void>thenApply(infoList -> {
  • 转换返回值:

    return (Void) null;

当然,你可以两者都做,但那是多余的。


查看完整回答
反对 回复 2023-08-16
  • 2 回答
  • 0 关注
  • 97 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信