Omitting Parameter Types
You'll learn when and how to skip parameter types in lambda expressions, letting the compiler figure them out for you.
Why Omit Types?
You've learned that you can declare parameter types explicitly in lambdas:
Function<String, Integer> lengthFunction = (String s) -> s.length();
But Java's type inference system is smart enough to deduce these types from context. Since the Function<String, Integer> declaration already says "input is String," you can simply write:
Function<String, Integer> lengthFunction = s -> s.length();
How Context Provides Types
Think of it like filling out a form where some fields auto-populate based on previous answers. When you assign a lambda to a functional interface variable, the interface's generic types tell the compiler exactly what parameter types to expect.
The compiler looks at:
- The target functional interface (
Predicate<String>,BiFunction<Integer, Integer, Integer>, etc.) - The abstract method's signature
- What types must flow in and out
When to Omit Types
Omit types when:
- The context makes them obvious
- You want cleaner, more readable code
- Single or multiple parameters with clear meaning
BiFunction<Double, Double, Double> multiply = (x, y) -> x * y;
Predicate<Integer> isEven = n -> n % 2 == 0;
Consumer<String> printer = msg -> System.out.println(msg);
Remember the Rules
You learned earlier: it's all or nothing. Either omit all parameter types or declare all of them—no mixing.
Key Takeaway: Omitting parameter types makes lambdas concise and readable; rely on Java's type inference when the functional interface context clearly defines what types the lambda receives.