Target Type from Method Parameters
You'll learn: How the Java compiler figures out what type your lambda expression should be when you pass it into a method.
The Core Idea
When you pass a lambda expression as an argument to a method, the compiler looks at the method's parameter type to determine what functional interface your lambda should implement. This is one of the most common ways target typing works in practice.
Think of it like fitting a puzzle piece into a slot: the shape of the slot (the method parameter type) tells you exactly what shape the piece (your lambda) needs to be.
How It Works
When you write something like:
list.forEach(item -> System.out.println(item));
The compiler:
- Sees
forEachexpects aConsumer<T>parameter - Checks that your lambda
item -> System.out.println(item)matchesConsumer's abstract method signature - Automatically treats your lambda as a
Consumerimplementation
Multiple Parameters Example
public void processList(Predicate<String> tester) {
// uses tester
}
public void processList(Function<String, Integer> mapper) {
// uses mapper
}
// Compiler uses parameter type to resolve overload:
processList(s -> s.isEmpty()); // Predicate (returns boolean)
processList(s -> s.length()); // Function (returns Integer)
The method signature eliminates ambiguity—the compiler knows which overloaded version you're calling based on what type your lambda returns.
Why This Matters
You don't have to explicitly cast or declare the lambda's type. The method parameter provides the target type context, making your code cleaner and more readable.
Key Takeaway: The compiler determines a lambda's functional interface type by examining the method parameter it's being passed to—the parameter signature provides all the context needed for type inference.