0

Given an Optional that is holding a Function<String, Boolean>, I cannot apply this Function out of the Optional via map/flatMap:

Optional<Function<String, Boolean>> optTestFunction = Optional.of(x -> true);
optTestFunction.flatMap(f -> f.apply("Test")).orElse(false);

The IDE as well as the java compiler are giving me this error:

no instance(s) of type variable(s) U exist so that Boolean conforms to Optional<? extends U>

Honestly, I do not get why it does not work like this - I have the feeling I am missing something obvious, but since even Google has not been able to help me with this one, I hope you can.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

1

Use .map(..) and not flatMap.

optTestFunction
    .map(f -> f.apply("Test"))
    .orElse(false);

A flatMap is used when the map step returns an Optional. It is not the case here.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79