Java泛型解惑:extends与super,CompletionStage thenApply参数疑问
? super T for the Function's input? Great question—this is a common point of confusion with Java generics, especially when dealing with functional interfaces like Function in the context of CompletionStage. Let’s break this down using the PECS principle (Producer Extends, Consumer Super), which is the key to wrapping your head around this.
First, let’s recall what thenApply does: it takes the result of the CompletionStage (which is of type T) and passes that result to a Function you provide. The job of this Function is to consume the T instance (take it as input) and produce a new result of type R.
Now, let’s compare the two generic bounds you’re asking about:
If we used ? extends T instead of ? super T
This would mean the Function could only accept subtypes of T. But wait—the CompletionStage gives us a T, not a subtype of T. For example:
- Suppose
TisObject, and we have aFunction<String, Integer>that calculates string lengths. We can’t pass anObjectto this function (since not allObjects areStrings), so this perfectly valid function would be incompatible with ourCompletionStage<Object>. That’s a needless restriction that limits flexibility.
Why ? super T is the right choice
Using ? super T means the Function can accept T or any supertype of T. Since T is a subtype of all its supertypes, we can safely pass the T result from the CompletionStage to this function. Let’s use the same example:
- If we have a
CompletionStage<String>that completes with"hello", aFunction<Object, Integer>that doesobj -> obj.toString().length()works perfectly. SinceStringis anObject, we can pass theStringdirectly to this function without any casting or safety issues.
This design choice makes thenApply far more flexible. It lets you reuse existing functions that operate on supertypes of T, instead of forcing you to write a new function specifically tailored to T. It’s a perfect application of the PECS rule: when a component is consuming a type (taking it as input), we use super.
内容的提问来源于stack exchange,提问作者user3385957

