2

Let's assume the following class hierarchy:

class A{}
class B extends A{}
class C extends B{}
class D extends C{}

In Java, it is possible to define wildcards with generics like this:

List<? extends A> aOrDown;//A or any subtype of A
List<? super D> dOrUp;//D or any supertype of D

Is it possible to bind the same wildcard to both an upper and lower bound?

I would imagine something like this:

List<? extends A super B> combined;
List<? extends A & super B> combined;

However, those seem to raise a compile-time error.

Is there any way to do bind a generic wildcard to a specific part of the class hierarchy?

I am interested whether this is possible in theory, I don't have a practical use-case for this.

dan1st
  • 12,568
  • 8
  • 34
  • 67
  • From a type theory point of view, this looks sound to me as long as you don't do something like `? extends B & super A`. `combined` would act as a producer of `A` and a consumer of `B`, but this is not a feature of Java. I guess implementing this would make the compiler a lot more complicated - the criteria for determining assignment compatibility need to be completely revised. And I don't see much benefit this feature would bring anyway. – Sweeper Apr 07 '22 at 10:28

1 Answers1

3

Section 4.5.1 of the JLS specifies the syntax for generic wildcards:

TypeArguments:
  < TypeArgumentList >
TypeArgumentList:
  TypeArgument {, TypeArgument}
TypeArgument:
  ReferenceType
  Wildcard
Wildcard:
  {Annotation} ? [WildcardBounds]
WildcardBounds:
  extends ReferenceType
  super ReferenceType

In here, WildcardBounds is written in square brackets. In Section 2.4 of the JLS, it is explained that in this context, square brackets indicate optional elements that can be put only once:

The syntax [x] on the right-hand side of a production denotes zero or one occurrences of x. That is, x is an optional symbol. The alternative which contains the optional symbol actually defines two alternatives: one that omits the optional symbol and one that includes it.

For bounded generic wildcards, this means that only one wildcard bound is permitted.

dan1st
  • 12,568
  • 8
  • 34
  • 67