Lesson · Lambdas & Functional Interfaces
Lambda expressions: syntax, capture, and the this that surprises people
15 min readLambda Expressions
A lambda is a behavior with a body you write and a type the compiler infers from context. Get the syntax variants and the capture rules straight, and every functional API reads plainly.
Anatomy of the syntax
Every lambda has three parts: a parameter list, an arrow, and a body. Each part has short forms, and all of them mean the same thing to the compiler.
Parentheses may be dropped only around a single inferred parameter. Types on parameters may be omitted (almost always should be), and the body may be a single expression or a block with braces.
(a, b) -> a + b // two inferred parameters, expression body x -> x * x // one parameter, parentheses optional () -> System.out.println("go") // no parameters (int a, int b) -> a - b // explicit types allowed, rarely needed x -> { // block body: needs an explicit return int y = x * 2; return y; }
Lambda anatomy · three parts, many spellings
click a partParameter list. Types are inferred from the target interface. Parentheses drop only for a single parameter; a parameter cannot shadow a local of the same name.
One inferred parameter may drop its parentheses. The moment you add a type or var, the parentheses come back.
Types come from context, not from the lambda
A lambda has no type of its own. It is typed by the context where it appears: an assignment, a method argument, a return. Change the target interface and the same syntax means different parameter types.
This is also why a bare lambda cannot be passed to Object-taking APIs, and why the same lambda written twice is not the same object.
Comparator<String> byLength = (a, b) -> a.length() - b.length(); // a and b are String BinaryOperator<String> join = (a, b) -> a + b; // same syntax, String too // (a, b) -> a + b cannot stand alone: the compiler has nothing to infer types from
Capturing: the value goes with the lambda
A lambda may read local variables from the enclosing method, but only if they are final or effectively final. The lambda copies the value when it is created; reassigning the variable afterwards would create an invisible second copy, so the compiler refuses the case outright.
Fields and array elements are exempt: they live on the object or the array, so lambdas read them live. That exemption is the usual way people work around the rule, sometimes too casually.
String prefix = "id-"; Supplier<String> next = () -> prefix + 42; // fine: prefix never reassigned int count = 0; Runnable r = () -> count++; // does not compile: count is reassigned // error: local variables referenced from a lambda expression must be final or effectively final
this means the enclosing instance
This is the difference that bites in training videos and equals()-style code: inside a lambda, this is the object around the lambda, not some hidden object for the lambda itself. An anonymous class, by contrast, always creates its own this.
The same goes for the class: a lambda has no class you wrote, no fields to declare, and no way to shadow the enclosing context with its own member access.
class Handler { String name = "outer"; void show() { Runnable anonymous = new Runnable() { @Override public void run() { // this refers to the anonymous Runnable System.out.println(this.getClass().getSimpleName()); } }; Runnable lambda = () -> System.out.println(this.name); // outer's name anonymous.run(); // empty name, anonymous class lambda.run(); // outer } }
Scope rules worth memorizing
Lambdas are strict about names, because they already see everything around them.
BiFunction<Integer, Integer, Integer> max = (var a, var b) -> Math.max(a, b);
- Parameters cannot shadow locals. If the method already has a local named a, a lambda parameter named a is a compile error.
- A lambda's body is not a class body. No fields, no methods, no constructors inside it. One method is all it implements.
- var is allowed on parameters (Java 11). It lets you add annotations without writing the type, and requires parentheses on every parameter once used.
- No default values, no varargs tricks. The parameters are exactly the SAM's parameters.
- Break, continue and return belong to the body's own boundaries. A return inside a block body returns from the lambda, not from the enclosing method.
Choosing the shape at the call site
The most common read of any functional API is: which part of my lambda lands where. For a Comparator, the two parameters are the pair being compared; for a Function inside map, the single parameter is one element of the stream. Reading the signature first, then writing the lambda, is the whole skill.
A lambda is a value description, not a method. It is created where the assignment happens, captures what it needs, and runs when the target interface's method is invoked.
Effectively final is about time, not intent
The rule exists because the capture happens once, at creation. One assignment before the lambda is fine; any assignment after it, even inside an if the compiler cannot prove is dead, makes the variable non-final and the lambda illegal. Move the mutable state into a field or a single-element array if you truly need it.
Interview angles
What are the three parts of a lambda, and which short forms exist?+
Parameters, arrow, body. Parentheses are optional around one inferred parameter; parameter types are optional; the body is either an expression or a braced block with explicit returns. Everything else is a variation of these three choices.
Does a lambda have a type of its own?+
No. It has a shape the compiler matches against the target functional interface. That is why the same syntax can implement Comparator<String> or BinaryOperator<String>, and why a bare lambda cannot be assigned to Object.
Why must captured locals be effectively final?+
The lambda captures the variable's value at creation. If reassignment were allowed, readers could not tell which value the lambda sees, and updates after capture would silently not appear. The compiler rejects the ambiguity.
What does this mean inside a lambda?+
The enclosing instance, exactly as if the code were written there directly. Anonymous classes give you a new this, which is a classic source of bugs when migrating a callback.
Can a lambda parameter shadow a local variable?+
No. Lambdas already see the enclosing scope, so a parameter with the same name would be ambiguous. The compiler reports that the variable is already defined in scope.