Return type inference: no unique maximal instance exists difference between 1.6 and 1.7 javac.

Dawid Weiss dawid.weiss at gmail.com
Mon Nov 29 02:53:01 PST 2010


Hi everyone,

I've had a somewhat heated debate with a friend of mine, concerning
type inference rules and differences between javac and ecj. For
example, the following code:

    public <A> A x() {
        return null;
    }

    public <B> void y() {
        B o = x();
    }

Compiles cleanly under ecj and javac 1.7 (latest snapshot), but fails
with an error under javac 1.6 (regardless of the version):

Inference.java: type parameters of <A>A cannot be determined; no
unique maximal instance exists for type variable A with upper bounds
B,java.lang.Object
        B o = x();

Interestingly, this does compile on all compilers:

    public <A> A x() {
        return null;
    }

    public <B> void y() {
        List<B> o = x();
    }

and so does this:

    public <A> List<A> x() {
        return null;
    }

    public <B> void y() {
        List<B> o = x();
    }

Could anybody be so kind and address the following questions:

1) Is the difference between javac 1.6 and 1.7 a bug in 1.6's
compiler? I checked a few past snapshots for 1.7 and they all worked,
so it must be a change done a good while ago. If this was a bug at
some point, is there a bugs parade entry for it anywhere (I did search
for something matching this, but couldn't find anything).

2) We both tried to formally prove the above code correct or incorrect
wrt the Java specification, but the complexity of type inference
rules, especially in assignment expressions, is, ehm, overwhelming. We
would appreciate if somebody could explain what the actual process of
inferring the type of B (or A) is in the above example; I have so far
assumed methods like this:

public <A> A x() {
        return null;
}

are roughly equivalent  to a forced cast (on the caller's side) to
whatever the method return value is assigned to.

Dawid

P.S. These code snippets are meant to be small, but the actual bug (?)
manifested itself in a large project, so it is a real use case, not
only academic discussion.



More information about the compiler-dev mailing list