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

Target Type from Cast Expressions

Using explicit casts to resolve ambiguous lambda target types.

Target Type from Cast Expressions

You'll learn how to use explicit type casts to clarify which functional interface a lambda expression should implement when the compiler can't figure it out on its own.

The Problem: Ambiguous Lambda Targets

Sometimes Java's type inference system encounters situations where a lambda expression could match multiple functional interfaces. When this happens, the compiler throws an error because it can't determine which type you intended. This ambiguity typically arises when:

  • Multiple overloaded methods accept different functional interfaces with compatible signatures
  • Generic contexts don't provide enough information
  • You're assigning a lambda without sufficient context

Cast Expressions to the Rescue

An explicit cast tells the compiler exactly which target type you want. By wrapping your lambda in parentheses and prefixing it with (TargetType), you remove all ambiguity:

// Ambiguous without cast - compiler doesn't know which overload
process((Predicate<String>) s -> s.isEmpty());

// Clear target type from cast
Runnable r = (Runnable) () -> System.out.println("Hello");

Think of it like giving someone directions: if they're confused about which road to take, you explicitly point and say "Take this road" — leaving no room for misinterpretation.

Common Scenarios

Cast expressions are particularly useful when:

  1. Overloaded methods accept different functional interfaces with similar lambda signatures
  2. Generic method calls where type parameters can't be inferred
  3. Complex expressions where contextual information is too distant
// Force interpretation as specific functional interface
Object obj = (Supplier<String>) () -> "result";

Key Takeaway: Use explicit casts like (FunctionalInterface) lambda to resolve ambiguous target types when the compiler can't infer which functional interface you intend your lambda expression to implement.