Why do the utility factory methods often use a specific generic parameter (like T
) instead of a bounded wildcard parameter (like ? super T
)?
For instance, the signature of Functions#forPredicate is:
public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate)
Why not use:
public static <T> Function<T, Boolean> forPredicate(Predicate<? super T> predicate)
Which would make something like the following possible?
Predicate<Number> isPositivePredicate = ...
Function<Integer, Boolean> isPositiveInteger = Functions.forPredicate(isPositivePredicate);
// above line is compiler error:
// Type mismatch: cannot convert from Function<Number,Boolean> to Function<Integer,Boolean>
Is it because consumers of Function
and Predicate
are expected to have the necessary bounded wildcard parameters to make this unnecessary? For example, the generic bounds on Iterables#find would allow a Predicate<Number>
to be used on a Iterable<Integer>
:
public static <T> T find(Iterable<T> iterable,
Predicate<? super T> predicate)
Are there other reasons?
Yes, it's absolutely accurate that we expect the consumers to have the right bounded wildcard parameters, but a couple additional reasons spring to mind:
T
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With