Proposal: Type inference for variable definition/initialization using the 'auto' keyword.
Joseph D. Darcy
Joe.Darcy at Sun.COM
Thu May 14 22:40:54 PDT 2009
Tim Lebedkov wrote:
> Type inference for variable definition/initialization using the 'auto' keyword.
> AUTHOR(S): Tim Lebedkov
> Provide a two sentence or shorter description of these five aspects of
> the feature:
> FEATURE SUMMARY: Should be suitable as a summary in a language tutorial.
> This proposal addresses the addition of type inference for
> variable definitions to the Java programming language using the 'auto'
> keyword instead of specific type name.
> For example, consider the following assignment statement:
> Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
> This is rather lengthy, so it can be replaced with this:
> auto anagrams = new HashMap<String, List<String>>();
> and anagrams is automatically typed as HashMap<String, List<String>>
> MAJOR ADVANTAGE: What makes the proposal a favorable change?
> Generics have had a tremendously positive impact on type safety in the
> Java programming language. They have made it possible to provide
> static guarantees about the type of instances used by other classes,
> preventing entire classes of runtime errors from occurring. However,
> generics have added complexity to Java, making the code far more
> verbose and occasionally difficult to read. Although solving this
> problem is well outside the scope of this proposal, a limited form of
> type inference would remove unnecessary redundancy from the language.
> Even without generics it seems unnecessary to duplicate type names for
> simple variable definitions/assignments like:
> Integer a = new Integer(1023);
> MAJOR BENEFIT: Why is the platform better if the proposal is adopted?
> Less code and no duplication has a positive impact on many things:
> - faster typing/faster code changes
> - easier code changing without IDE assistance
> - code versioning diffs are more clear
> MAJOR DISADVANTAGE: There is always a cost.
> - it could be harder to read the code.
> - auto will be a keyword and may break some old code
> ALTERNATIVES: Can the benefits and advantages be had some way without
> a language change?
Catching up on proposal comments, I think the core benefits of using
"auto" or "final" on the left hand side for variables are achieved with
the diamond operator that allows one to elide type parameters on the
right hand side. IMO, the diamond solution of specifying the variable
type fully on the left and then specifying only the implementation type
without redundant, repeated type parameters on the right is more in
keeping with Java coding style.
More information about the coin-dev