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

Target Type from Variable Declarations

Assigning lambdas to explicitly typed variables and how the type is resolved.

Target Type from Variable Declarations

You'll learn how the compiler determines a lambda's functional interface type from the variable it's assigned to.

The Core Idea

When you assign a lambda expression to a variable with an explicitly declared type, the compiler uses that variable's type as the target type to figure out what functional interface the lambda should implement. The variable declaration provides the necessary context for type inference.

Think of it like filling out a form: the blank space (variable type) tells you what kind of information (lambda signature) to write.

How It Works

When you write:

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

The compiler sees Predicate<String> on the left side and knows:

  • The lambda must implement Predicate<String>'s test method
  • The parameter s must be a String
  • The lambda must return a boolean

You're explicitly telling Java: "This lambda should be a Predicate<String>." The compiler validates that your lambda expression matches that contract.

Multiple Possibilities, One Declaration

The same lambda syntax could theoretically match different functional interfaces. The variable type disambiguates:

Function<String, Integer> getLength = s -> s.length();
ToIntFunction<String> getLen = s -> s.length();

Both lambdas look identical, but the variable declarations make clear which functional interface each implements.

Why This Matters

Variable declarations are one of the primary ways Java resolves lambda types. Without an explicit type (whether from a variable, method parameter, or return type), the compiler can't infer what functional interface you intend to use.

Key Takeaway: When you assign a lambda to an explicitly typed variable, that variable's type becomes the target type, telling the compiler which functional interface to implement and enabling complete type inference for the lambda's parameters and return type.