Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics name clash

Consider:

public interface Foo<T> {
    public static class X{}
    public void foobar(T t); 
}

public class Bar<X> {
    Foo<X> foo = new Foo<X>() {
        public void foobar(X t) {}
    };
}

I found no way to express that I mean the X from Bar<X> and not Foo.X in the foobar(X t) implementation. Is there no other way than renaming the generic parameter X in Bar or the static inner class?

like image 923
Landei Avatar asked Jan 21 '12 16:01

Landei


1 Answers

I don't think there is a way to disambiguate to the type parameter, and I think that that was a reasonable design decision to make.

  1. The conventions are clear that type parameters should be one character long if possible, and the flipside to this is that other classes shouldn't have one-character names.
  2. If you had the ability to disambiguate, then you would have the ability to rename the type parameter X in Bar<X>. In other words, if you had the ability to say foobar(TypeParameter.X t) you would have the ability to simply use something other than X for the type parameter on Bar. Renaming X is the way you avoid name clashes.

Don't forget that type parameter names don't leak out to other classes in more than trivial ways. You are never forced to use a certain type parameter name, ever. So it makes sense that the language designers wouldn't have thought this is worth adding complexity to the language for.

like image 123
Mark Peters Avatar answered Sep 28 '22 06:09

Mark Peters