8

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?

matts
  • 6,738
  • 1
  • 33
  • 50

2 Answers2

6

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:

  • In general, we don't widen the types of generic methods until we have a specific reason to. This policy has paid off several times.
  • Java's type inference isn't always up to figuring out more advanced generics automatically, so keeping the narrower generics reduces the number of users who need to explicitly specify T.
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • re. first point doesn't that just push the consumer to cast which is the worse of two evils? Also curious, when you say "we" do you mean you've developed on this or just the software community in general. – djechlin Jan 31 '13 at 17:53
  • More specifically - how has this policy paid off in practice? At present the only situations in which I can imagine it mattering, the consumer would just bypass with casting to derived type. – djechlin Jan 31 '13 at 17:54
  • When I say "we," I mean that I'm on the Google Java Core Libraries Team which develops Guava. But the consumer should never need to cast: a `Predicate super T>` can always be used directly, anywhere you'd use a `Predicate`. There's no need to cast; they can be applied to exactly the same values. – Louis Wasserman Jan 31 '13 at 18:03
  • @LouisWasserman Thanks for the great answer. I'm also curious if you'd have any specific examples where maintaining a narrow type paid off. One of my concerns is (theoretically) having to use a `Predicate` with some third-party code that hasn't declared the wildcard nicely, which seems to me might then require either a wrapper to "upcast" the parameter, or an explicit cast on the `Predicate` itself. But I suppose I could see it getting quite confusing when multiple wildcards are involved, so I guess avoiding that hassle as much as possible is probably wise :) – matts Jan 31 '13 at 19:33
2

In the find() example, T can always be inferred unambiguously.

In the forPredicate[1]() example, T can also be inferred unambiguously.

In the forPredicate[2]() example, there's uncertainty what T should be. If the result of the method is assigned to a target type, T can be determined from the target type. Otherwise it's a little head scratching:

forPredicate(isPositive).apply(42);  // T is a subtype of Number, but which one?

In java5/6, it shouldn't compile. (well I tested it on java 6 and it does compile, but it's probably a bug, since java 6 also compiles forPredicate(p).apply("str"))

Java 7 improved a little bit, and the new rule happens to dictate that T=Number. It works, but it feels more like an arbitration for the sake of it.


Ideally, we shouldn't need to worry about wildcards. If I need a predicate for my integers, I should declare a Predicate<Integer> parameter. The fact that a Predicate<Number> argument would also be acceptable is another story. It should be the compiler's job to convert Predicate<Number> to Predicate<Integer> - we can do it without overhauling existing java generics type system, a new conversion rule is all that's needed. One can also provide a conversion library

Predicate<Number>  pn = ...;
Predicate<Integer> pi = convert(pn);

Iterable<Integer> iter1 = ...;
Iterable<Number>  iter2 = convert(iter1);

All convert() methods can be generated mechanically.


Java 8 make things a little easier. We still cannot do

Predicate<Number>  pn = n -> n.intValue()>0;
Predicate<Integer> pi = pn;  // error!

but we can do

Predicate<Integer> pi = pn::test;  // ok
// it means        pi = (Integer i)->pn.test(i)

also

Function<Integer, Boolean> f = pn::test;   // ok

which is equivalent to f = forPredicate[2](pn). In java 8 we'll rarely need forPredicate() etc to convert between functional types.

irreputable
  • 44,725
  • 9
  • 65
  • 93
  • There isn't a problem with `forPredicate(isPositive).apply(42)`, though—in this case `T` is the most specific type it can be, `Number`. `Integer` inherits from `Number`, so the `apply` call is fine. If it's compiling when you pass in a string though, it kind of sounds like it was compiled with rawtypes or something. – matts Jan 31 '13 at 22:53
  • My thought is: let's say I have a private `Predicate` in my class, and I want to return it from a method as a `Function`, I shouldn't have to expose to callers that it's really a `Predicate`. And since it accepts all `Number`s, it will also accept all `Integer`s. To do this now, I'd have to convert it with a wrapper class or an explicit class. – matts Jan 31 '13 at 22:56
  • the politically correct answer would be that your method return type should be `Function super Integer, Boolean>` instead. this is just too ugly. – irreputable Jan 31 '13 at 23:07
  • Do you mean `Function extends Integer, Boolean>`? It accepts `Integer` and sub-types, not `Integer` and super-types. – matts Jan 31 '13 at 23:10
  • no, it's a function that accepts `X`, where `X` is an unknown super type of `Integer`. since the function accepts `X`, it accepts `Integer` – irreputable Jan 31 '13 at 23:18