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

Parameter Type Declaration: Explicit Types

Specify explicit parameter types in lambda expressions when type inference is insufficient or clarity is needed.

Parameter Type Declaration: Explicit Types

What You'll Learn

You'll learn when and how to explicitly declare parameter types in lambda expressions instead of relying on Java's type inference.

The Core Idea

Up until now, you've likely written lambdas like (x, y) -> x + y, letting Java infer that x and y are whatever types the functional interface requires. But sometimes you want—or need—to be explicit about parameter types by declaring them yourself: (Integer x, Integer y) -> x + y.

Think of it like ordering coffee: saying "the usual" works when the barista knows you, but explicitly saying "medium latte with oat milk" removes any ambiguity.

When to Use Explicit Types

For clarity: When the lambda is complex or the context isn't obvious, explicit types make your code self-documenting:

BiFunction<String, Integer, String> repeat = 
    (String str, Integer n) -> str.repeat(n);

When type inference fails: Occasionally, the compiler cannot infer types, especially with overloaded methods or complex generics. Explicit types resolve ambiguity.

For consistency: In a team codebase with style guidelines, explicit types might be preferred for uniformity.

The Rule

When you declare types explicitly, you must:

  • Declare types for all parameters (no mixing)
  • Keep parentheses around the parameter list
// Valid: all explicit
BinaryOperator<Integer> add = (Integer a, Integer b) -> a + b;

// Invalid: cannot mix inferred and explicit
// (a, Integer b) -> a + b  // Won't compile!

Key Takeaway: Explicitly declaring parameter types in lambdas enhances clarity and resolves ambiguity, but you must declare all parameters consistently—you cannot mix inferred and explicit types in the same lambda.