You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java泛型解惑:extends与super,CompletionStage thenApply参数疑问

Why does CompletionStage's thenApply use ? 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 T is Object, and we have a Function<String, Integer> that calculates string lengths. We can’t pass an Object to this function (since not all Objects are Strings), so this perfectly valid function would be incompatible with our CompletionStage<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", a Function<Object, Integer> that does obj -> obj.toString().length() works perfectly. Since String is an Object, we can pass the String directly 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:49:47