How can my method return a value computed within a lambda expression?

Viewed 709

Here's a simplified version of what my code looks like:

public void pairing() {
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            JsonObject pairing = response.result().body().toJsonObject(); // what I want to return
        }
}

This makes a POST request to localhost:6660/request, and I create a new JsonObject called pairing that stores the response to that request. I could process pairing inside of the lambda expression for the request, but ideally, I would be able to return the JsonObject to the method that calls pairing() and process it from there.

I tried this:

public JsonObject pairing() {
    JsonObject pairing = new JsonObject();
    WebClient web = WebClient.create(vertx);
    String url = "/request";
    JsonObject obj = new JsonObject();
    web
        .post(6660, "localhost", url)
        .sendJsonObject(obj, response -> {
            pairing = response.result().body().toJsonObject();
        }
    return pairing;
}

But it doesn't work because I get the "pairing must be final or effectively final" error. Is there some way I can return "pairing" from this method so that I can access it elsewhere in my program? Or am I possibly approaching this the wrong way?

1 Answers
Related