Sub topic 11
var in lambda parameters
This chapter assumes you know basic lambda syntax, functional interfaces such as Function and BiFunction, and how var infers types for ordinary local variables. Java 11 added one more place where var is allowed: the formal parameters of a lambda expression. This chapter covers the syntax, the rules, what the compiler infers, and why you would use it.
What the feature is
A lambda parameter list can take three forms:
| Form | Example | Name |
|---|---|---|
| No types | `(a, b) -> a + b` | Implicitly typed |
| Declared types | `(Integer a, Integer b) -> a + b` | Explicitly typed |
| `var` | `(var a, var b) -> a + b` | `var` parameters |
The var form is not a new kind of typing. The compiler handles (var a, var b) like the implicit form (a, b). It takes the parameter types from the target type, which is the functional interface the lambda is assigned to or passed as. A lambda is not a standalone expression, so it always needs a target type.
import java.util.function.BiFunction;
public class VarLambda {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> add = (var a, var b) -> a + b;
System.out.println(add.apply(2, 3)); // 5
}
}BiFunction<Integer, Integer, Integer> declares that apply takes two Integer arguments. The compiler infers a and b as Integer, and a + b is checked against that.
How the parameter types are inferred
The target type supplies the types. The var in a lambda does not look at an initializer, because there is none. This differs from var on a local variable.
import java.util.List;
import java.util.Map;
public class VarLambdaInference {
public static void main(String[] args) {
Map<String, Integer> stock = Map.of("apples", 3);
// k is String, v is Integer, taken from Map.forEach's BiConsumer<? super K, ? super V>
stock.forEach((var k, var v) -> System.out.println(k.toUpperCase() + " " + (v + 1)));
List<String> names = new java.util.ArrayList<>(List.of("Grace", "Al", "Barbara"));
names.sort((var x, var y) -> x.length() - y.length());
System.out.println(names); // [Al, Grace, Barbara]
}
}Map.forEach expects a BiConsumer<? super String, ? super Integer>. The target type has wildcards, and the compiler derives the lambda's function type from it by the rules in the Java Language Specification for functional interface parameterization. For ? super String, the parameter type becomes String. So k.toUpperCase() compiles, and v + 1 unboxes the Integer.
The rules
The compiler enforces these rules. Each one is a compile-time error if broken.
- All or nothing. If one parameter uses
var, every parameter in that lambda must usevar. You cannot mixvarwith an implicit name or with an explicit type. - Parentheses are required. A lone implicit parameter may omit them (
x -> x * 2), but avarparameter may not: write(var x) -> x * 2. - No array brackets. Neither
var[] xnorvar x[]is allowed, as with localvar. - A target type is still required. A
varparameter does not remove the need for one. - Zero-parameter lambdas have nothing to mark.
() -> 42stays as it is.
import java.util.function.BiFunction;
import java.util.function.Function;
public class VarLambdaRejected {
public static void main(String[] args) {
// None of the commented lines compile:
// BiFunction<Integer, Integer, Integer> a = (var x, y) -> x + y; // mixed var and implicit
// BiFunction<Integer, Integer, Integer> b = (var x, Integer y) -> x + y; // mixed var and explicit
// Function<Integer, Integer> c = var x -> x * 2; // parentheses required
// Function<int[], Integer> d = (var x[]) -> x.length; // brackets not allowed
// var e = (var x) -> x * 2; // no target type
Function<Integer, Integer> ok = (var x) -> x * 2;
System.out.println(ok.apply(21)); // 42
}
}The last commented line, var e = (var x) -> x * 2;, fails for two reasons that stack. The local var cannot infer a type from a lambda initializer, and the lambda has no target type from which to infer x. Giving the variable an explicit functional interface type fixes both.
Why bother: modifiers and annotations
An implicit lambda (a, b) -> ... is already shorter than (var a, var b) -> .... So why does var exist here? Because an implicit parameter list cannot carry modifiers or annotations. Once you add one, Java requires a type on that parameter, and then the rule "all or nothing" makes you type every parameter. Before Java 11 this meant writing out the full types, which could be long.
var gives you a type slot that costs almost nothing to write.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.function.BiFunction;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@interface NonNegative {}
public class VarLambdaModifiers {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> sum =
(@NonNegative var a, final var b) -> a + b;
System.out.println(sum.apply(4, 5)); // 9
}
}Here a carries an annotation that a tool such as a nullness checker or a validation framework could read. b is final, so assigning to it inside the body is an error. The same lambda with implicit parameters would not compile at all if you tried to add @NonNegative or final.
What stays the same
Switching a lambda between (a, b) and (var a, var b) does not change behavior.
- Inferred types. Both forms get the same parameter types from the target.
- Overload resolution. The compiler treats a lambda with
varparameters as implicitly typed, like one with no parameter types. In an overloaded call it has the same limits as an implicit lambda, so it may not be enough to choose between overloads on its own. An explicitly typed lambda can disambiguate in some cases where an implicit orvarlambda cannot. - Bytecode.
varexists only in source. The compiled lambda has concrete parameter types and nothing in the class file records that you wrotevar. - Runtime. There is no dynamic typing. If the target type says
Integer, the parameter is anIntegerfor the lambda's whole body.
This also explains an easy mistake to make. Writing var does not let the lambda accept more types. The parameter is as strictly typed as in the explicit form.
import java.util.function.Function;
public class VarLambdaStrict {
public static void main(String[] args) {
Function<String, Integer> length = (var s) -> s.length();
// length.apply(42); // would not compile: 42 is not a String
System.out.println(length.apply("hello")); // 5
}
}Common errors
- Adding
varto only one parameter when you wanted a single annotation. Annotate that parameter and putvaron all the others too. - Dropping the parentheses on a single
varparameter.var x -> ...is a syntax error. - Expecting
varto infer from the body. The lambda body never influences the parameter types. If the target type is a generic method's parameter and the compiler cannot work out its type arguments, you get an inference error, andvarcannot rescue it. Supply a type argument or a typed variable. - Using
varwhere it adds nothing. If you do not need a modifier or an annotation, the plain(a, b) -> ...is shorter and equally typed. Most teams usevarparameters only when they need an annotation orfinal.
Summary of decisions
| Situation | Prefer |
|---|---|
| Short lambda, obvious types, no modifiers | `(a, b) -> a + b` |
| Need `@Annotation` or `final` on parameters | `(@Ann var a, final var b) -> ...` |
| Long lambda where the parameter types are not obvious | `(String a, int b) -> ...` |
| Single parameter with a `var` | `(var x) -> ...`, never `var x -> ...` |
Exercise
Which of these lambdas compile when assigned to a BiFunction<Integer, Integer, Integer>? (1) (var a, var b) -> a * b (2) (var a, b) -> a * b (3) (final var a, final var b) -> a * b (4) var a, var b -> a * b
Show answer
Lambdas 1 and 3 compile. Lambda 2 mixes var with an implicit parameter, which is not allowed. Lambda 4 is a syntax error because the parameter list is not in parentheses. In lambdas 1 and 3, both a and b are inferred as Integer from the target type.
Exercise
A teammate writes var square = (var x) -> x * x; and asks why it fails. Explain the problem and give a corrected version that squares an Integer.
Show answer
A lambda needs a target type, and var on the left gives it none, because var infers from the initializer and a lambda initializer has no standalone type. Without a target type, the parameter x also has no type to infer. Declare the variable with a functional interface: Function<Integer, Integer> square = (var x) -> x * x;. Then x is an Integer.
Exercise
Why would you choose (var a, var b) over (a, b) when both give the same types and the same bytecode?
Show answer
Because only the var form lets you put an annotation or the final modifier on a parameter without writing out the full type. An implicit parameter cannot carry a modifier or annotation, and an explicit type would be longer. If you need neither, the implicit form is simpler.