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

Target Type and Contextual Information

How the compiler determines the functional interface type from assignment context, method arguments, or return statements.

Target Type and Contextual Information

You'll learn: How the Java compiler figures out which functional interface your lambda implements by looking at where you use it.

The Compiler's Detective Work

When you write a lambda expression, you don't explicitly say "this is a Predicate" or "this is a Function." Instead, the compiler plays detective, examining the context where your lambda appears to determine its target type — the functional interface it must match.

The compiler looks for clues in three main places:

Assignment Context

Predicate<String> isEmpty = s -> s.isEmpty();

The variable type Predicate<String> tells the compiler what functional interface to expect.

Method Argument Context

list.removeIf(s -> s.isEmpty());

The compiler checks removeIf's signature, sees it expects Predicate<T>, and types your lambda accordingly.

Return Statement Context

public Function<Integer, String> getFormatter() {
    return n -> String.valueOf(n);
}

The method's return type tells the compiler the lambda must be a Function<Integer, String>.

Why This Matters

This contextual inference is what makes lambdas concise. You write s -> s.isEmpty() once, and it can be a Predicate<String> in one place, but if the context expected Function<String, Boolean>, the same-looking lambda would have different meaning.

Think of it like filling out forms: The same piece of information (your lambda) fits into different labeled boxes (functional interfaces) depending on which form (context) you're completing.

Key Takeaway: The compiler determines a lambda's target functional interface type by examining the assignment variable, method parameter, or return type where the lambda is used — not from the lambda expression itself.