var in Lambda Parameters (Java 11+)
You'll learn how to use var in lambda parameters to annotate them while keeping Java's type inference working for you.
The Core Idea
Starting with Java 11, you can use var for lambda parameters instead of explicit types or no type at all. Why would you do this? The main reason is to add annotations to lambda parameters. Without var, you can't annotate parameters when relying on type inference—you'd have to write explicit types, which is verbose. With var, you get the best of both worlds: concise type inference plus the ability to annotate.
When You Need This
Imagine you want to mark a parameter as @NonNull or @Nullable in a lambda. Before Java 11, you had only two choices:
- Use type inference (no annotations allowed):
(x, y) -> x + y - Declare explicit types (verbose):
(String x, String y) -> x + y
Now with var, you can do this:
BiFunction<String, String, String> concat =
(@NonNull var x, @NonNull var y) -> x + y;
The compiler still infers the types (String in this case), but you've added annotations to enforce your constraints.
Consistency Rule
Important: If you use var for one parameter in a lambda, you must use it for all parameters. Mixing isn't allowed:
// ❌ Not allowed: mixing var and inferred
(var x, y) -> x + y
// ✅ Correct: all parameters use var
(var x, var y) -> x + y
Key Takeaway: Use var in lambda parameters (Java 11+) when you need to annotate parameters while preserving type inference; all parameters must use var if any do.