Target Typing with Generic Methods
You'll learn how Java's target typing works together with type inference to deduce both lambda types and generic type parameters in a single method call.
The Double Inference Challenge
When you call a generic method and pass a lambda expression, Java's compiler faces a two-part puzzle: it must infer both the generic type parameters of the method and the functional interface type of your lambda. Target typing and type inference work hand-in-hand to solve both simultaneously.
Think of it like fitting puzzle pieces together from both ends—the method signature provides clues about what types are expected, and your lambda's structure provides clues about what you're supplying. Java matches them up to figure out the complete picture.
How It Works
Consider a generic method like this:
public static <T> void process(Function<T, String> converter, T value) {
System.out.println(converter.apply(value));
}
When you call it with a lambda:
process(x -> x.toString(), 42);
Java infers:
- Generic type
T=Integer(from the argument42) - Lambda's parameter type
x=Integer(from target typeFunction<Integer, String>)
The context flows in both directions—the second argument helps determine T, which then completes the target type for the lambda.
Why This Matters
This dual inference lets you write clean, concise code without redundant type annotations. The compiler uses all available contextual clues—return types, parameter positions, and argument types—to resolve everything automatically.
Key Takeaway: Target typing with generic methods allows Java to simultaneously infer generic type parameters and lambda types, using contextual information from both the method signature and the arguments you provide.