Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Establishing correlations between type parameters

Assume that we have two generic Java interfaces: Foo<T> and Bar<T>, of which there may be many implementations. Now, assume that we want to store one of each in a single class, both using the same value for T, but keep the exact implementations typed:

public interface FooBar<T, TFoo extends Foo<T>, TBar extends Bar<T>> {
    TFoo getFoo();
    TBar getBar();
}

Above, T is used for the sole purpose of enforcing that TFoo and TBar's classes use the same type parameter. Adding this type parameter to FooBar seems redundant for two reasons:

  1. FooBar doesn't actually care about T at all.
  2. Even if it did, T can be inferred from TFoo and TBar.

My question is therefore if there is a way to enforce conditions like this without cluttering up FooBar's list of type parameters. Having to write FooBar<String, StringFoo, StringBar> instead of the theoretically equivalent FooBar<StringFoo, StringBar> looks ugly to me.

like image 448
BambooleanLogic Avatar asked Aug 01 '13 12:08

BambooleanLogic


1 Answers

Unfortunately, there is no better way... The compiler needs the T type to be declared in order to use it and there is no other place to declare it :

EDIT : unrelated link

If bound A is not specified first, you get a compile-time error:

 class D <T extends B & A & C> { /* ... */ }  // compile-time error

(extract from this doc)

And this is a little out of the subject, but this doc defines the conventions on type parameters names as being single, uppercase letters.

like image 152
gtinon Avatar answered Oct 01 '22 19:10

gtinon