Why does the Optional isPresent class method take Consumer<? super T> as a parameter, not Consumer<T>?

Viewed 94

I'm reading about wildcard and I'm a little confused.I don't really understand why the ifPresent method needs ? super T . public void ifPresent(Consumer<? super T> consumer) Why doesn't just T work?

I've read about PECS and it's clear how it works for class methods, for example,but why is it here in the interface, I'll be glad to help.

1 Answers

The most likely reason is to allow Consumers of a type broader than T (which is a type that is compatible with T) to be able to be used for the consumer argument.

Here's an example:

Optional<String> opt = Optional.of("abc");
Optional<Integer> intOptional = Optional.of(2);

Consumer<Object> printConsumer = System.out::println;
opt.ifPresent(printConsumer);
intOptional.ifPresent(printConsumer);

printConsumer is just a function that prints objects. So it works with both String and Integer types.

If ifPresent took only Consumer<T>, one would not be able to write code as the above, because one can't use Consumer<Object> where Consumer<String> or Consumer<Integer> is required. But in cases where a consumer instance already exists and is compatible with multiple T types, Consumer<? super T> makes it possible to reuse the consumer instance.

Related