2

Suppose you have a generic class

class MyClass<T> { ... }

You can force T to extend or implement a class or an interface, respectively, by writing

class MyClass<T extends ThisClassOrThisInterface> { ... }

You can even make this construction fully parametric, by abstracting on ThisClassOrThisInterface, namely

class MyClass<U, T extends U> { ... }

My question is: Is there a way to force T to be a parameterized type? For instance, in a way that

class AnotherClass extends MyClass<List<?>>

shall be fine, because List is a generic type, but

class AnotherClass extends MyClass<Object>

shall not, because Object cannot be parameterized over any type.


I was trying to understand how much you can play with generics. In particular, I was trying to implement the following class (pretend that <T<?>> forces T to be a generic type):

class MyClass<T<?>> {

    <A> Function<A, T<A>> myMethod() { ... }

}
  • As far as I can tell this isn't (currently) possible. But I also can't imagine a situation where you want a rather open generic T (without any boundaries) but still require it to be generic. If you expect something specific and want to support certain behaviour, then you can add boundaries. For example, when you want your `T` to be a collection type: `class MyClass>` – Tom Dec 25 '20 at 19:06
  • @Tom Well, if it were possible, then you would be able to design the `Monad` interface –  Dec 25 '20 at 19:32
  • 2
    Yeah, that definitely isn't possible. Java doesn't support higher-kinded types. – Louis Wasserman Dec 25 '20 at 22:43

0 Answers0