2

Suppose I have some Java code like this (won't compile):

class MyGenericClass<T extends SomeInterface, U extends SomeClass & T>{}

The trouble is, I can't declare U as is, because when listing bounds, the class must come first, and T might be a class. Is there an obvious work around here? If not, it seems that you'd be forced into doing unchecked casts sometimes, which is unfortunate.

Mark VY
  • 1,489
  • 16
  • 31
  • 1
    Do you need the specific `T` in your class's logic, or do you just care that `T` extends `SomeInterface`? – rgettman Nov 08 '18 at 22:51
  • need T as the return type of a public method – Mark VY Nov 08 '18 at 22:53
  • Lets say `T` gets specified as class how will Java be able to allow `U` extend both SomeClass and that `T` class. – tsolakp Nov 08 '18 at 23:04
  • 1
    If `T` is a class, it _must_ be either a superclass or a subclass of `SomeClass`, or there's no possible `U`. Do you know which one it will be? – Louis Wasserman Nov 08 '18 at 23:05
  • T is an ancestor of U – Mark VY Nov 08 '18 at 23:13
  • 1
    @MarkVY the compiler thinks that it might be a class and hence complaining, but actually in your use-case, is it always an interface or can it be a class as well? – Kartik Nov 08 '18 at 23:16
  • Why does your class need to return an object as `T` and not as `SomeInterface`? Maybe you should restructure the class hierarchy. I don't think we can help you further without more context on why you need to keep this invariant – flakes Nov 08 '18 at 23:25
  • What is `SomeClass & T` ? Are you allowed to use `&` in Generics, never seen it before? – Koray Tugay Nov 08 '18 at 23:37
  • @Kartik it's always either SomeInterface, or else SomeFancierVersionOfTheInterface. Pretty sure it's never a concrete class, though I might be wrong. – Mark VY Nov 08 '18 at 23:40
  • Related: https://stackoverflow.com/questions/197190/why-cant-i-use-a-type-argument-in-a-type-parameter-with-multiple-bounds – tsolakp Nov 08 '18 at 23:41
  • @flakes : why should the caller be forced to write explicit casts? – Mark VY Nov 08 '18 at 23:43
  • @KorayTugay https://docs.oracle.com/javase/tutorial/java/generics/bounded.html – Mark VY Nov 08 '18 at 23:44
  • 1
    @MarkVY I see, thanks. Never seen it before.. – Koray Tugay Nov 09 '18 at 00:30

0 Answers0