I have a generic method
public <K extends Number> K get()
{
...
}
When I call this method, I use a syntax like:
Integer i = instance.<Integer>get();
However, this is also legal:
Integer i = instance.get();
My question is, is the second method call a form of type inference in Java?
Yes, this is type inference based on the assignment type. It's specified in section 15.12.2.8 of the JLS:
If any of the method's type arguments were not inferred from the types of the actual arguments, they are now inferred as follows.
- If the method result occurs in a context where it will be subject to assignment conversion (§5.2) to a type S, then let R be the declared result type of the method, and let R' = R[T1 = B(T1) ... Tn = B(Tn)] where B(Ti) is the type inferred for Ti in the previous section, or Ti if no type was inferred.
Then, a set of initial constraints consisting of:
- the constraint S >> R', provided R is not void; and
- additional constraints Bi[T1 = B(T1) ... Tn = B(Tn)] >> Ti, where Bi is the declared bound of Ti,
is created and used to infer constraints on the type arguments using the algorithm of section (§15.12.2.7). Any equality constraints are resolved, and then, for each remaining constraint of the form Ti <: Uk, the argument Ti is inferred to be glb(U1, ..., Uk) (§5.1.10).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With