Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

the compiler wont even bother to determine if you meant Foo.X, it will consider the TypeParameter X, regardless, unless you typed something like:

public class Bar<X> {
    Foo<X> foo = new Foo<X>() {
        public void foobar(Foo.X t) {}
    };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top