Course contentsShow
← Java
Lesson 1733 of 2,87036. Lambda Expressions and Method ReferencesFree lesson

Target Typing with Generic Methods

How target typing interacts with type inference in generic method calls.

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:

  1. Generic type T = Integer (from the argument 42)
  2. Lambda's parameter type x = Integer (from target type Function<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.