Could the compiler reasonably infer type parameters?
Yes in the example situation - static HashMap<K,V>newInstance(){return new HashMap<>();}
is obviously short for static < K extends Object , V extends Object > HashMap<K,V>newInstance()return new HashMap<K,V>();}
.
But if your compiler inferred type parameters, then your code would still compile even when you mistype class names. static void setName ( Sting name )
is probably wrong but your compiler would assume you meant <Sting extends Object> static void setName ( Sting name );
Through the magic of runtime erasure that would be equivalent to static void setName ( Object name ) ;
.
If the method is not static, then inference becomes problematic. class X { HashMap<K,V>newInstance(){return new HashMap<>();}}
could be type-inferred as one of the following:
class X <K extends Object , V extends Object> { HashMap<K,V>newInstance(){return new HashMap<>();}}
class X <K extends Object > { < V extends Object > HashMap<K,V>newInstance(){return new HashMap<>();}}
class X <V extends Object> { < K extends Object > HashMap<K,V>newInstance(){return new HashMap<>();}}
class X { <K extends Object , V extends Object> HashMap<K,V>newInstance(){return new HashMap<>();}}
In addition, if type parameters were inferred then what is the order. When they are explicitly stated, the order is obvious. The only (obvious to me) way to solve the order problem for inferred type parameters is the order they were declared in the code. But if you just reverse the order of 2 lines of code (which should be inconsequential) you could potentially change the public interface breaking the build. So brittle!