Convert Java CompletionStage to Scala Equivalent

Viewed 163

I'm trying to convert below java code into its scala equivalent

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;

In Scala, I converted CompletionStage to Scala Future and need help with fold function. Does the below conversion look good and is that the correct way to extract XContainer from futureResponse?

    val apiResponseF: CompletionStage[GetXByKeyResponse] = appleClient.getAppleProperty(key)

    val futureResponse: Future[GetXByKeyResponse] = scala.compat.java8.FutureConverters.toScala(apiResponseF)

    futureResponse.onSuccess(resp => resp.fold(???, ???, ???))

Definition of fold method:

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 Answers
Related