Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the type inference algorithm tries to find the most specific type?

Tags:

java

generics

From Oracle's documentation of Type Inference

Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.

To illustrate this last point, in the following example, inference determines that the second argument being passed to the pick method is of type Serializable:

static <T> T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList<String>());

Why the algorithm tries to find the most specific type ?

like image 205
Geek Avatar asked Feb 26 '13 06:02

Geek


1 Answers

Because assignment compatibility would make the invocation ambiguous if this rule were not enforced.

For instance, PrintStream defines print(Object) and print(String) if the rule of the most specific type were not enforced, print("bar") could invoke print(Object) instead of print(String), which would be counterintuitive.

Note that type selection is based on compile-time types, so in the following example print(Object) is invoked:

PrintStream out = ...;
Object bar = "bar";
out.print(bar);
out.print((Object)"foo");
like image 136
Javier Avatar answered Sep 27 '22 22:09

Javier