News for hackers. Stuff that matters.
Re:Background: how we got the generics we have (2020) by vimax on Friday April 02, 2021 @05:13PM (#26676059)
That's close, but not quite what I want. The Iterator example starts to break down, but I want to pass in a subclass of Iteratable and get that subclass back.

class SpecialIterator<R> extends Iterator<R>{}

SpecialIterator<String> strings =...;

SpecialIterator<Integer> ints = process(string, magicFunc);

The Iterator example starts to break down, so here's a more concrete example:

I have 3 classes: AbstractTester, StringTester, and ListTester

class AbstractTester<R, T extends AbstractTester<R, ? super T>>

class StringTester<R> extends AbstractTester<R, StringTester<R>>

class ListTester<R, T extends AbstractTester<R, ? super T>>

I want to make a method in AbstractListTest like this: public <Z> T<Z> convert(Z z)

I have supporting code in my classes to create an return an instance of type T<Z>, but I cannot express the type T<Z> in the type system. The type parameter T can extend something with a type parameter, and be passed a type with a type parameter, but it cannot be defined to have a type parameter itself.

This is for a fluent api framework, where I need the compiler to know the type T<Z> without casting

I can do something like this: public <Z, Y extends AbstractTester<Z, ? super T>> Y convert(Z z);

but that will return an AbstractTester<Z> which can be cast to a StringTester<Z>, but the compiler does not know it is a StringTester<Z>

A subclass of AbstractTester is not required to have any type parameters itself. Converting a T to a T<Z> would not be legal for a T without a type parameter. To do what I want, Java would need to add a new type bounds operator to restrict a type parameter to subclasses with a particular type parameter.

Java would need to allow me to define ListTester like this to restrict T to only subclasses with a type parameter:

class ListTester<R, T<_> extends AbstractTester<_, ? super T<_>>

I'd love to be wrong, and would be very grateful to find a way to do this.

There are no comments on this comment yet.