Because I am learning haskell, and I know that there is monads, and I know that Optional in Java is monad, and maybe Mono in your code is a monad too, I really want to answer this question.
I learned from a video that monad is approximately equal to
- functor with flatten, or
- flatMap
In my opinion, monad is some kind of container/box that hold object with extra state of that object.
The example code in the video, is about parsing a string and return a parsed, divided number. Return of the function will be Optional.empty if any of the step is not finished(like parse non digit string to number, in another words, value in Optional is not presented
):
public Optional<Double> codeWithoutFlatMap(String s){
final Optional<String> split = split(s);
if (split.isPresent()) {
final Optional<Double> parse = parse(split.get());
if (parse.isPresent()) {
final Optional<Double> result = divide(parse.get());
if (result.isPresent()) {
return result;
}
}
}
return Optional.empty();
}
With flatMap, the code is much more precise
// this code is exactly equal to code before
public Optional<Double> codeWithFlatMap(String s){
return split(s)
.flatMap(split -> parse(split))
.flatMap(parse -> divide(parse));
}
Back to your case, I notice some code can be improved, it is the cause for not compiling:
- flatMap returns boxed type, for example Optional<Response> or Mono<Response>, you expect method would return a Response, but actually it returns a Mono<Response>
- the Function inside flatMap, should return a boxed type, like Mono<Response>