Sub topic 4
How the Compiler Knows a Lambda's Type
A lambda such as s -> s.length() does not name its own type. It does not say "I am a Function" or "I am a Comparator". The compiler still has to give every lambda a type, and it works that type out from the code around the lambda. This chapter shows how.
The Target Type
The target type is the type the surrounding code expects at the place where you wrote the lambda. It must be a functional interface. The compiler reads the target type and then checks the lambda against that interface's single abstract method.
From that one method, the compiler learns three things:
- How many parameters the lambda must have.
- What types those parameters are. This is called type inference: the compiler fills in types you did not write.
- What the lambda must return, or that it must return nothing (
void).
If the lambda does not match, the code does not compile.
Where Target Types Come From
A lambda can only appear in places that supply a target type. The four most common places are listed below.
| Context | Example | Target type comes from |
|---|---|---|
| Assignment | `StringCheck c = s -> s.isEmpty();` | The variable's declared type |
| Method argument | `runTwice(() -> ...)` | The method's parameter type |
| Return statement | `return (a, b) -> ...;` | The method's return type |
| Cast | `(Runnable) () -> ...` | The type in the cast |
A Worked Example
This program uses all four contexts. Save it as TargetTyping.java and run it.
import java.util.Comparator;
public class TargetTyping {
interface StringCheck {
boolean check(String s);
}
interface StringToNumber {
int convert(String s);
}
static void runTwice(Runnable task) {
task.run();
task.run();
}
static Comparator<String> byLength() {
// Return context: the target is Comparator<String>,
// so a and b are inferred to be String.
return (a, b) -> a.length() - b.length();
}
public static void main(String[] args) {
// Assignment context: s is inferred to be String.
StringCheck isEmpty = s -> s.isEmpty();
StringToNumber length = s -> s.length();
System.out.println(isEmpty.check("")); // true
System.out.println(length.convert("hello")); // 5
// Method argument context: the target is Runnable.
runTwice(() -> System.out.println("Hi")); // Hi (printed twice)
// Return context, used through the Comparator.
System.out.println(byLength().compare("fig", "apple") < 0); // true
// Cast context: Object is not a functional interface,
// so the cast supplies the target type.
Object task = (Runnable) () -> System.out.println("From a cast");
((Runnable) task).run(); // From a cast
// This line would NOT compile: check must return boolean,
// but s.length() gives an int.
// StringCheck bad = s -> s.length();
}
}Look at isEmpty and length. You never wrote String s, but the compiler knew s was a String because both check and convert take a String.
The Same Lambda, Different Types
Because the type comes from the context, one piece of lambda text can become different types. The lambda () -> System.out.println("Hi") is a Runnable when passed to runTwice. Assigned to some other interface with a no-argument void method, it would be that interface instead. The lambda's shape stays the same, and the target decides what type it becomes.
Exercise
Given interface Doubler { int twice(int n); }, will Doubler d = n -> n * 2; compile? What type does the compiler infer for n, and how does it know?
Show answer
Yes, it compiles. The target type is Doubler, whose only abstract method is int twice(int n). The compiler reads that method, infers that n is an int, and checks that n * 2 produces an int, which matches the return type.
Exercise
Why does var greet = () -> System.out.println("Hello"); fail to compile, and what is one way to fix it?
Show answer
var asks the compiler to take the type from the right-hand side, but a lambda has no type until it has a target, so the compiler has nothing to work from. One fix is to declare a functional interface type, for example Runnable greet = () -> System.out.println("Hello");.