Explicit return in Block Bodies
You'll learn when you must include a return statement inside a multi-line lambda expression.
When your lambda uses a block body (curly braces with multiple statements), Java no longer automatically returns the result. Unlike single-expression lambdas where the value is implicitly returned, block bodies require you to explicitly use the return keyword if your functional interface expects a value.
The Core Rule
- Expression body:
x -> x * 2— the result is automatically returned - Block body:
x -> { return x * 2; }— you must writereturnexplicitly
Think of it like the difference between a quick verbal answer versus writing a formal letter. A quick answer doesn't need "My answer is..." preamble, but a structured document needs clear formatting to indicate what you're providing as the result.
When Explicit Return is Required
If your functional interface has a non-void return type (like Function, Predicate, Supplier), and you use braces, you must include return:
Function<Integer, Integer> square = x -> {
int result = x * x;
return result; // REQUIRED
};
Without return, the code won't compile — Java has no way to know which value you intend to send back.
When Return is Optional
If your functional interface returns void (like Consumer), no return is needed or expected:
Consumer<String> printer = s -> {
String formatted = s.toUpperCase();
System.out.println(formatted);
// No return needed - Consumer returns void
};
Key Takeaway: In lambda block bodies, always use explicit return statements when the functional interface expects a value; omit return only for void-returning interfaces.