将Java CompletionStage转换为等效的Scala
我正在尝试将下面的java代码转换为它的scala等价物
CompletionStage<GetXByKeyResponse> apiResponseF = appleClient.getAppleProperty(key);
CompletionStage<XContainer> xContainerF = apiResponseF.thenCompose(resp -> resp.fold(
CompletableFuture::completedFuture,
errorNotFound -> Futures.failedFuture(new Exception("some error")),
errorInternalServerError -> Futures.failedFuture(new Exception("some error"))
));
return xContainerF;
在Scala中,我将CompletionStage转换为Scala Future,并需要有关fold
函数的帮助。下面的转换看起来不错吗?这是从futureResponse
提取XContainer
的正确方法吗
val apiResponseF: CompletionStage[GetXByKeyResponse] = appleClient.getAppleProperty(key)
val futureResponse: Future[GetXByKeyResponse] = scala.compat.java8.FutureConverters.toScala(apiResponseF)
futureResponse.onSuccess(resp => resp.fold(???, ???, ???))
fold
方法的定义:
import java.util.function.Function;
public <T> T fold(Function<XContainer, T> handleOk,
Function<ServiceErrorResponse, T> handleNotFound,
Function<ServiceErrorResponse, T> handleInternalServerError) {
if (this instanceof Ok) {
return handleOk.apply(((Ok) this).getValue());
} else if (this instanceof NotFound) {
return handleNotFound.apply(((NotFound) this).getValue());
} else if (this instanceof InternalServerError) {
return handleInternalServerError.apply(((InternalServerError) this).getValue());
} else {
throw new AssertionError("This is a bug!");
}
}
共 (0) 个答案