Why Optional's or and flatMap method's supplier type parameter is a wildcard

  • A+

The Optional.or method was added in Java 9. This is the method signature

public Optional<T> or​(Supplier<? extends Optional<? extends T>> supplier) 

Why is the type parameter of the Supplier taking ? extends Optional rather than just Optional since Optional is a final class.

The same is true for Optional.flatMap method. This is a change from Java 8.

In Java 8, it was Function<? super T, Optional<U>> mapper wherease it was changed to Function<? super T,​? extends Optional<? extends U>> in Java 9.


I found the reasoning behind this from Stuart Marks himself


This has to do with nested generics (Optional is nested within Function). From the mail thread

 Function<..., Optional<StringBuilder>> 

is not a subtype of

 Function<..., Optional<? extends CharSequence>> 

To get around this, we have to add the outer wildcard as well, so that

 Function<..., Optional<StringBuilder>> 

is a subtype of

 Function<..., ? extends Optional<? extends CharSequence>> 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: