Mixing Explicit and Inferred Types (Not Allowed)
You'll learn why Java forbids mixing explicit type declarations with inferred types in the same lambda parameter list.
When writing lambda expressions, you've learned that you can either declare parameter types explicitly or let Java infer them. However, Java enforces a strict rule: you must be consistent across all parameters in a single lambda.
The Core Restriction
Java's lambda syntax requires an all-or-nothing approach to type declarations. You cannot specify types for some parameters while leaving others to be inferred in the same lambda expression. This restriction keeps the syntax unambiguous and the compiler's job straightforward.
Not allowed:
BiFunction<String, Integer, String> mixed =
(String name, age) -> name + age; // ❌ Compilation error
Correct alternatives:
// All inferred
BiFunction<String, Integer, String> inferred =
(name, age) -> name + age; // ✅
// All explicit
BiFunction<String, Integer, String> explicit =
(String name, Integer age) -> name + age; // ✅
Why This Matters
Think of it like a dress code: you can wear formal attire or casual attire, but you can't wear a tuxedo jacket with sweatpants. The compiler needs consistency to parse your lambda correctly. If you start declaring types, the compiler expects you to finish what you started for all parameters.
This rule prevents confusing situations where the programmer's intent becomes unclear and keeps lambda syntax clean and predictable.
Practical Impact
Choose one style and stick with it for all parameters in that lambda. Most developers prefer type inference for brevity, resorting to explicit types only when clarity demands it or when the compiler cannot infer types from context.
Key Takeaway: In a lambda parameter list, either declare types for all parameters or for none—mixing explicit and inferred types in the same lambda is a compilation error.