Java 8 propose some
improvements to the existing type-argument inference support that will
significantly reduce the need for explicit type-arguments in generic method
calls.
1.
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 of Integer ,
found List of Object
Unfortunately, this is
not allowed in JDK 5/6/7 -- the only option available to the programmer is to
use an explicit type-argument:
List.cons(42, List.nil());
It would be nice if
type-argument inference would be extended to consider the formal parameter type
in a method call (target typing).
2. Inference in chained calls
Another fairly common
problem is when generic method calls are chained together, as below:
String s = List.nil().head(); //error: expected String, found
Object
The right-hand type in
the above assignment is unused during type-argument inference -- as a result,
the only option for the programmer is (again) to manually specify
type-arguments, as in:
String s = List.nil().head();
Again, it would be nice
to remove the burden of explicit type-arguments by allowing the right-hand type
of the assignment (String) to flow through the chain of generic method calls.
No comments:
Post a Comment