tags:

views:

67

answers:

2

I'm trying to refactor a class and set of subclasses where the M type does extend anything, even though we know it has to be a subclass of a certain type. That type is parametrized and I would like its parametrized types to be available to subclasses that already have values for M.

Is there any way to define this class without having to include the redundant K and V generic types in the parameter list. I'd like to be able to have the compiler infer them from whatever M is mapped to by subclasses.

public abstract class NewParametrized<K, V, M extends SomeParametrized<K, V>> {

    public void someMethodThatTakesKAndV(K k1, V v1) { }
}

In other words, I'd like the class declaration to look something like:

 public class NewParametrized<M extends SomeParametrized<K, V>> {

And K and V's types would be inferred from the definition of M.

+1  A: 

The problem is that K and V aren't really "repeated", at least not any more than a variable declaration and a use of that same variable are "repetition".

The way to think of this is that you declare the generic types K and V, and then you use those declared generic types in the definition of the generic type M. So, you don't declare the generic type K or V more than once: Rather, you declare each of them once and then refer to them in a declaration of something else.

To look at it another way, the number of generic types here is still three, namely K, V, and M. M happens to be defined in terms of K and V, but you didn't have to define M that way.


I should add that if you are a proponent of type inference, you might view the declaration and the use of the same variable as unnecessary repetition. However, if you're accustomed to programming in Java (or C, or C++, or many, many other languages), then you're probably accustomed to declaring variables before you use them.

Joe Carnahan
I think he mainly means the repetition when using the class, not just the repetition in its declaration. Each time you refer to an instance of this class, you have to repeat the same. Like `NewParametrized<String, Integer, SomeParametrized<String, Integer>>`. Both String/Integer occurrences are uses, not declarations.
Wouter Coekaerts
Good point - I hadn't thought about it from the perspective of the users of the class, just from the perspective of the author. That verbosity is unfortunate, even if it makes sense in the context of the class declaration.
Joe Carnahan
A: 

If it were possible, the declaration

public class NewParametrized<M extends SomeParametrized<K, V>> {

would be ambiguous if a K or V class were defined in the same package, it would be impossible to know whether it is a type variable or a reference to the concrete class.

Santi P.