[英]Trying to update a CompletableFuture variable but get error : local variables referenced from a lambda expression must be final or effectively final
public CompletableFuture<String> description() {
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> "Search for: " + this.stop + " <-> " + name + ":\n")
.thenApply(x -> x += "From " + this.stop + "\n");
CompletableFuture<Void> temp = services.thenAccept(x -> {
for (BusService service : x.keySet()) {
CompletableFuture<Set<BusStop>> stops = x.get(service);
result = result.thenApply(y -> y += describeService(service, stops));
}
});
return result;
}
public CompletableFuture<String> describeService(BusService service,
CompletableFuture<Set<BusStop>> stops) {
return stops.thenApply(x -> {
if (x.isEmpty()) {
return "";
}
return x.stream()
.filter(stop -> stop != this.stop)
.reduce("- Can take " + service + " to:\n",
(str, stop) -> str += " - " + stop + "\n",
(str1, str2) -> str1 + str2);
});
}
I was trying to update the result
in the forloop in description()
, since result.thenApply()
results in a new CompletableFuture instance, I need to reassign it to a new variable in order to update result
, but i am not very sure how我试图在description()
的 forloop 中更新result
,因为result.thenApply()
导致一个新的 CompletableFuture 实例,我需要将它重新分配给一个新变量以更新result
,但我不太确定如何
You don't need to reassign it to a new variable, and you shouldn't.您不需要将其重新分配给新变量,您也不应该这样做。 Combine the futures instead.取而代之的是合并期货。
return services.thenCombine(result, (x, y) -> {
for (BusService service : x.keySet()) {
CompletableFuture<Set<BusStop>> stops = x.get(service);
y += describeService(service, stops);
}
return y;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.