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

What Is Target Typing?

Understanding how the compiler infers a lambda's functional interface type from context.

What Is Target Typing?

You'll learn: How the Java compiler automatically figures out which functional interface a lambda expression implements based on where you use it.

The Context-Driven Detective

Target typing is the compiler's ability to infer a lambda's functional interface type from the context in which it appears. Instead of you explicitly declaring what type your lambda is, the compiler looks at the "target" location—the method parameter, variable assignment, or return statement—and deduces the appropriate functional interface.

Think of it like a smart waiter who knows what drink you want based on which table you're sitting at. The location (context) tells them everything they need to know.

How It Works

When you write a lambda expression, you're not declaring its type directly. The compiler examines:

  • Variable declarations: What type is being assigned?
  • Method arguments: What parameter type does the method expect?
  • Return statements: What return type does the method signature declare?
  • Cast expressions: What type are you explicitly casting to?

The compiler matches your lambda's signature (parameters and return type) to the abstract method of the functional interface in that context. This is why the same lambda syntax can work with Predicate<String>, Function<String, Boolean>, or a custom functional interface—the target determines the type.

Why It Matters

Target typing is what makes lambdas so flexible and concise. You don't repeat type information that's already obvious from context. The compiler does the detective work, ensuring type safety while keeping your code clean.

Key Takeaway: Target typing lets the compiler infer a lambda's functional interface type from where it's used, eliminating redundant type declarations while maintaining full type safety.