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

Mixing Explicit and Implicit Types: Not Allowed

Learn that you must declare types for all parameters or none when writing lambda expressions.

Mixing Explicit and Implicit Types: Not Allowed

What you'll learn: You'll discover why Java enforces an all-or-nothing rule when declaring parameter types in lambda expressions.

The All-or-Nothing Rule

When writing lambda expressions, Java gives you flexibility: you can explicitly declare parameter types, or you can let the compiler infer them. However, there's one strict requirement: you must be consistent within a single lambda expression. You cannot mix explicit and implicit types for different parameters—it's all declared or all inferred.

Why This Restriction Exists

Think of it like a restaurant menu: you can order à la carte (choosing each item explicitly) or go with the prix fixe menu (letting the chef decide everything). But you can't mix both approaches for the same meal—you're either making all the decisions or trusting the system completely.

Java's compiler needs clarity. When inferring types, it analyzes the entire lambda context together. Allowing mixed declaration styles would create ambiguity and complicate the type inference algorithm unnecessarily.

What Works and What Doesn't

Valid - All implicit:

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

Valid - All explicit:

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

Invalid - Mixed (compilation error):

// This will NOT compile!
BiFunction<String, Integer, String> func3 = (String s, n) -> s.repeat(n);

The third example fails because s has an explicit type declaration while n relies on type inference.

Practical Impact

Choose your style based on clarity. Explicit types document intent but add verbosity. Implicit types are concise when context makes types obvious. Just remember: commit to one approach per lambda.

Key Takeaway: In lambda expressions, all parameters must use explicit types or all must use implicit types—mixing both styles in the same lambda is a compilation error.