Sub topic 3
Java Local Variable Type Inference with `var`
Assume Java 10 or later, basic generics, loops, try-with-resources, and lambda expressions.
`var` Is a Reserved Type Name, Not a Keyword
var is a reserved type name. The compiler recognizes it only where a local variable type may appear. It is not a general Java keyword, so it can still be used as an identifier in some other contexts.
int var = 10; // legal identifier
System.out.println(var);You cannot use var as an explicit type. A declaration such as var count = 10; asks the compiler to infer the type from the initializer.
No Runtime Cost and No Dynamic Typing
Type inference happens during compilation. The compiled program still has a fixed static type, and the runtime does not inspect or change that type.
var count = 10; // statically typed as int
// count = "ten"; // compilation errorThe compiler checks method calls and assignments as it would for an explicitly declared int.
`var` in Lambda Parameters
Lambda parameters normally get their types from the functional interface. You may write var for lambda parameters when you need parameter annotations or want consistent syntax.
Every parameter in that lambda must use var. You cannot mix var with implicit or explicit parameter types.
import java.util.function.BiFunction;
public class LambdaVar {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> add =
(var left, var right) -> left + right;
System.out.println(add.apply(2, 3)); // 5
}
}Non-Denotable Types and Anonymous Classes
Some types cannot be written directly in Java source. An anonymous class is one example. var can infer its type, allowing access to members declared inside the anonymous class.
public class AnonymousVar {
public static void main(String[] args) {
var point = new Object() {
int x = 3;
int y = 4;
};
System.out.println(point.x + point.y); // 7
}
}The inferred type exists only for that local variable. It cannot be used as a method parameter or return type.
When to Use `var` and When Not To
Use var when the initializer makes the type clear or when the type cannot be written conveniently. Avoid it when the type communicates important meaning that the initializer hides.
- Prefer
var list = new ArrayList<String>();when the right side clearly identifies the type. - Prefer
List<String> list = loadNames();when the interface type documents the intended abstraction. - Avoid
var value = getValue();when the return type is not obvious. - Remember that
varrequires an initializer and one local declarator.
Exercise
Does var make a variable dynamically typed, and may a lambda mix var with implicit parameters?
Show answer
No. The compiler assigns one fixed static type. No, every parameter in that lambda must use var.