gpt4 book ai didi

java - 在 Futures.transform 中,使用 Function 和 AsyncFunction 有什么区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:42 25 4
gpt4 key购买 nike

我知道Function的apply方法是同步返回一个对象,AsyncFunction的apply是异步运行的,返回一个Future。

你能举个例子说明什么时候更喜欢什么吗。

我看到的一个代码片段看起来像这样:

Futures.transform(someFuture, new AsyncFunction<A, B>() {
public B apply(A a) {
if (a != null) {
return Futures.immediateFuture(a.getData())
} else {
return Futures.immediateFailedFuture(checkException(());
}
});
});

既然AsyncFunction里面的值是直接返回的,为什么这里还需要AsyncFunction呢?或者这只是我遇到的一个坏例子?

最佳答案

您找到的代码片段是一个错误的示例,因为它使用 AsyncFunction 来处理同步计算的内容。这是不必要的冗长。

使用标准的 Function 代码会更简洁:

Futures.transform(someFuture, new Function<A, B>() {
public B apply(A a) {
if (a != null) {
return a.getData();
} else {
throw checkException();
}
});
});

当将 A 转换为 B 的代码是异步的时,您应该使用 AsyncFunction。在您的示例中,代码最初可能是异步的,后来被一个程序员改为使用 Futures.immediateFuture()/Futures.immediateFailedFuture()不必费心用 Function 替换 AsyncFunction。或者他可能只是错过了重载方法。

关于java - 在 Futures.transform 中,使用 Function 和 AsyncFunction 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com