Parameterized Local Variable Type Inference – Generics

Parameterized Local Variable Type Inference

Consider the four local variable declarations shown below. The first three declarations are equivalent, as they create a Node<String> object whose data and next fields are null. In declaration (1), since the type String is explicitly specified in the object creation expression, the actual type parameter is deduced to be String. In declaration (2), the diamond operator is specified in the object creation expression, but the compiler is able to infer that the actual type parameter is String from the left-hand side of the declaration—that is, the compiler considers the context of the whole declaration. In the case of the parameterized local variable declarations with var, both the actual type parameters and the parameterized type denoted by var are inferred from the object creation expression.

Click here to view code image

// Parameterized local variable declarations:
Node<String> node1 = new Node<String>(null, null); // (1) Node of String
Node<String> node2 = new Node<>(null, null);       // (2) Node of String
var node3 = new Node<String>(null, null);          // (3) Node of String
var node4 = new Node<>(null, null);                // (4) Node of Object

In declaration (3), as String is explicitly specified in the object creation expression, the actual type parameter is inferred to be String and the parameterized type of node3 denoted by var is inferred to be Node<String>.

However, in declaration (4), the diamond operator is used in the object creation expression. In this case, the actual type parameter is inferred to be Object and the parameterized type of node4 denoted by var is inferred to be Node<Object>. Adequate type information should be provided in the object creation expression when declaring parameterized local variables with var in order to avoid unexpected types being inferred for the actual parameter types and the parameterized type denoted by var.

Leave a Reply

Your email address will not be published. Required fields are marked *