java 8 lambda tech question for jsonpath library

Viewed 149

I'm looking info about lambda although I'm not able to find something similar to below function. It belongs to class org.springframework.test.web.servlet.result.JsonPathResultMatchers , and ResultMatcher is a @FunctionalInterface, and result is type MvcResult and jsonPathHelper.doesNotExist return void

public ResultMatcher doesNotExist() {
    return result -> jsonPathHelper.doesNotExist(getContent(result));
}

I call above one through

jsonPath("$._embedded" ).doesNotExist()

I have literally no idea about:

  1. if jsonPathHelper.doesNotExist return void then why doesNotExist return ResultMatcher.

  2. Class has anything similar to result, where is this argument come from?

Thanks

1 Answers

The lambda in your code:

result -> jsonPathHelper.doesNotExist(getContent(result));

is just a representation of a ResultMatcher since its a FunctionalInterface. You can look at it as if :

public ResultMatcher doesNotExist() {
    return new ResultMatcher() {
        @Override
        public void match(MvcResult result) throws Exception {
            jsonPathHelper.doesNotExist(getContent(result)); // returns void
        }
    };
}

if jsonPathHelper.doesNotExist return void then why doesNotExist return ResultMatcher

Your method doesNotExist, just returns the functional interface in itself, which can thereafter be used to invoke its match function. Note that invocation would also be returning void.

Class has anything similar to result, where is this argument come from?

If you look at the anonymous class above, with lambda representation the result becomes the argument of the match method within the ResultMatcher implementation.

So when you actually wish to access this implementation(or ResultMatcher in general), you would invoke the method as follows(simplified initializations):

ResultMatcher resultMatcher =  doesNotExist(); // your method returns here
MvcResult result = new MvcResult(); // some MvcResult object
resultMatcher.match(result); // actual invocation
Related