(original) (raw)
Title: Generalized target-type inference Author: Maurizio Cimadamore Organization: Oracle Created: 2011/2/22 Type: Feature State: Draft Exposure: Open Component: core/lang Scope: SE Discussion: compiler-dev@openjdk.java.net Template: 1.0 Summary ------- Improve the usability of generics by reducing method type-inference corner cases, and improve the readability of code by reducing explicit type-arguments in generic method calls. Motivation ---------- Type-arguments in generic method calls are automatically inferred by the compiler since JDK 5. Type-inference is important not only as explicit type arguments are somewhat awkward and verbose, but primarily because many programmers are unfamiliar with them and, as a result, are unable to cope with situations where type-argument inference fails to give the correct answer. It is thus important to minimize cases in which method type-inference fails; we believe method type-inference could be greatly improved by adding the support for following features (i) inference in argument position and (ii) inference in chained calls. Description ----------- Here we propose some improvements to the existing type-argument inference support that will significantly reduce the need for explicit type-arguments in generic method calls. i. Inference in argument position Consider the following class declaration: class List { static List nil() { ... }; static List cons(Z head, List tail) { ... }; E head() { ... } } The result of a generic method, such as List.nil() may be inferred from the right-hand side of an assignment: List ls = List.nil(); The compiler's type-inference mechanism figures out that the type-argument to the List.nil() call is indeed String. It seems reasonable that the compiler should be able to infer the type when the result of such a generic method invocation is passed to another method, as below: List.cons(42, List.nil()); //error: expected List, found List