Summary
Type inference, the ability of the compiler to infer the type of variables, can reduce finger typing, and potentially simplify source code. In a recent blog post, Neal Gafter proposes constructor type inference for Java.
Advertisement
Even those who believe in the benefits of strongly-typed languages readily admit that source code in a staticly-typed language tends to be longer than similar code in a dynamic language would be, in part due to the added type information developers must specify.
Bill Venners recently described a technique used by some statically typed languages, such as Scala, for the compiler to infer the type of variables automatically, Programming with "Duh" Typing.
Neal Gafter published a blog post almost coincidentally with Venners' essay, on proposing a similar facility for the Java language, Constructor Type Inference:
I propose a new form of class instance creation expression:
Map<String,List<Thing>> map = new HashMap<>();
Using empty type parameters on a class instance creation expression asks the language/compiler to perform type inference, selecting appropriate type parameters...
Type inference today works on the right-hand-side of an assignment. I also propose that we enable this new form to be used in more situations by improving type inference for expressions appearing in other contexts:
the argument of a method call
the receiver of a method call
the argument of a constructor
the argument of an alternate constructor invocation
This would enable generic methods to be invoked in these contexts without providing explicit type parameters.
What do you think of Gafter's proposal to add type inference to Java constructors?
yes, i would highly appreciate (with a compiler-flag to explicitely turn this behaviour off). Would keep the code more readable. We could even bring this to the extreme by allowing
public class Foo{
public Map<String,List<Integer>> aMethod(){ ... }
}
Foo anObject = new Foo();
Map<> resultMap = anObject.aMethod();
which would create a correctly typed Map for the local variable.
This would make a lot of people very happy. This is one of my biggest pet peeves in Java 1.5 and greater. It may seem trivial but these redundant declarations really junk up ones source and provide no benefit.
I have to assume that wildcards would not be allowed on the left-hand side in this kind of assignment, right?