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

Poly Expressions and Context Sensitivity

Understanding lambdas as poly expressions that derive meaning from surrounding context.

Poly Expressions and Context Sensitivity

You'll learn: How lambda expressions act as "poly expressions" that adapt their meaning based on the surrounding code context.

What Is a Poly Expression?

In Java, a poly expression (short for polymorphic expression) is an expression whose type isn't determined by the expression itself, but rather by the context in which it appears. Lambda expressions are the primary example of poly expressions.

Think of a lambda like a chameleon: it changes to fit its environment. The same lambda syntax x -> x * 2 can represent an IntUnaryOperator, a Function<Integer, Integer>, or even a LongUnaryOperator, depending entirely on what the surrounding code expects.

Context Is King

The context provides the target type that the compiler uses to interpret the lambda. This context can come from:

  • A variable declaration: IntUnaryOperator op = x -> x * 2;
  • A method parameter: list.replaceAll(x -> x * 2);
  • A return statement: return x -> x * 2;
  • A cast expression: (Function<Integer, Integer>) (x -> x * 2)

Without context, the compiler has no way to determine what functional interface the lambda should implement. That's why you can't simply write var mystery = x -> x * 2; in isolation—the compiler needs the surrounding clues to figure out the lambda's type.

Why This Matters

This context sensitivity is what makes lambdas so flexible and reusable. The exact same lambda syntax can serve different purposes depending on where you place it. The compiler does the heavy lifting, using target typing to match your lambda to the appropriate functional interface.

Key Takeaway: Lambdas are poly expressions—they derive their type and meaning entirely from the surrounding context, making them adaptable to different functional interfaces with identical syntax.