Sub topic 4
How the Compiler Knows a Lambda's Type
A lambda like (a, b) -> a + b does not say what type it is. It has no class name and no interface name, and often its parameters have no types either. Java still checks it fully at compile time. This chapter shows how the compiler works out a lambda's type from the code around it.
The Big Idea: Target Typing
A target type is the type that the surrounding code expects a value to have. For a lambda, the target type must be a functional interface, which is an interface with exactly one abstract method.
The compiler reads the lambda in this order:
- It looks at where the lambda appears and finds the expected type.
- It checks that this type is a functional interface.
- It finds that interface's single abstract method.
- It uses that method's parameter types and return type to check the lambda.
This process is called target typing. A lambda takes its type from where it is used, and it cannot have a type on its own.
One Lambda, Two Meanings
Because the type comes from outside, the same lambda text can mean different things in different places. Look at (a, b) -> a + b below.
interface IntMath {
int combine(int a, int b);
}
interface TextMath {
String combine(String a, String b);
}
public class SameLambda {
public static void main(String[] args) {
IntMath add = (a, b) -> a + b; // a and b are int
TextMath glue = (a, b) -> a + b; // a and b are String
System.out.println(add.combine(2, 3)); // 5
System.out.println(glue.combine("2", "3")); // 23
}
}In the first line, the target type is IntMath. Its method takes two int values, so a and b are int, and + adds numbers. In the second line, the target type is TextMath, so a and b are String, and + joins text. The lambdas are written the same way, but they compile to different code.
Where a Target Type Can Come From
A lambda is legal only in a place that supplies a target type. These places are called contexts. A context is the position in the code where the lambda appears.
| Context | Example | Where the target type comes from |
|---|---|---|
| Assignment | `Shout a = s -> s.toUpperCase();` | The declared type of the variable |
| Method argument | `printShout(s -> s + "!!", "hey");` | The method's parameter type |
| Return statement | `return s -> s.toUpperCase() + "!";` | The method's declared return type |
| Cast | `(Shout) s -> s.trim()` | The type named in the cast |
This program uses all four contexts:
interface Shout {
String shout(String s);
}
public class Contexts {
static void printShout(Shout s, String text) {
System.out.println(s.shout(text));
}
static Shout makeShout() {
return s -> s.toUpperCase() + "!"; // return context
}
public static void main(String[] args) {
Shout a = s -> s.toUpperCase(); // assignment context
printShout(s -> s + "!!", "hey"); // method argument context: prints hey!!
Shout b = makeShout();
Object o = (Shout) s -> s.trim(); // cast context
System.out.println(a.shout("hi")); // HI
System.out.println(b.shout("wow")); // WOW!
System.out.println(((Shout) o).shout(" space ")); // space
}
}The cast line deserves a closer look. The variable o has type Object, and Object is not a functional interface. The cast (Shout) gives the lambda a real target type first. After that, the Shout object is stored in an Object variable, which is allowed for any object.
How Parameter Types Are Inferred
Type inference means the compiler works out a type that you did not write. With lambdas, the parameter types are usually inferred from the target's method.
Generics give the compiler the information it needs. Here the variable type Comparator<String> tells the compiler that compare takes two String values:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class InferenceDemo {
public static void main(String[] args) {
// a and b are inferred as String from Comparator<String>
Comparator<String> byLength = (a, b) -> a.length() - b.length();
// The same lambda with the types written out
Comparator<String> byLengthExplicit = (String a, String b) -> a.length() - b.length();
List<String> words = new ArrayList<>(Arrays.asList("banana", "fig", "apple"));
// No variable here: List<String>.sort expects a Comparator<String>,
// so a and b are String again.
words.sort((a, b) -> a.length() - b.length());
System.out.println(words); // [fig, apple, banana]
System.out.println(byLength.compare("hi", "hello")); // -3
System.out.println(byLengthExplicit.compare("hello", "hi")); // 3
}
}Look at the call words.sort(...). The list is a List<String>, so sort expects a Comparator<String>. That gives the lambda its target type, so you can call a.length() without writing any types.
When There Is No Target Type
If the compiler cannot find a target type, the lambda cannot compile. These two mistakes are the most common:
public class NoTarget {
public static void main(String[] args) {
// Object o = () -> System.out.println("hi");
// error: incompatible types: Object is not a functional interface
// var r = () -> System.out.println("hi"); // needs Java 10 or later for var
// error: cannot infer type for local variable r
// (lambda expression needs an explicit target-type)
// Fix: name a functional interface as the type
Runnable r = () -> System.out.println("hi");
r.run(); // hi
}
}The var keyword asks the compiler to infer the variable's type from the value. The lambda needs the variable's type to know its own type. Each one waits on the other, so the compiler gives up. Name the interface instead.
When the Lambda Does Not Fit the Target
A target type can exist and still not match the lambda. The compiler then reports an error at the lambda. These checks happen:
- Parameter count. The lambda must have as many parameters as the method.
Shout bad = (a, b) -> a;fails becauseshouttakes one parameter. - Return type. The body's value must fit the method's return type.
Shout bad = s -> s.length();fails with "bad return type in lambda expression: int cannot be converted to String". - Return or no return. If the method returns a value, every path through a block body must return one. If the method is
void, the body must not return a value withreturn x;.
The last rule has one exception. If the method is void, an expression body may still be a method call that returns something, and the returned value is thrown away:
import java.util.ArrayList;
import java.util.List;
public class VoidCompatible {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
// Runnable.run() returns void, but names.add returns boolean.
// This is allowed: the boolean result is simply ignored.
Runnable addOne = () -> names.add("Ada");
addOne.run();
System.out.println(names); // [Ada]
// Runnable bad = () -> 42;
// error: bad return type in lambda expression
// (42 is a plain value, not a statement, so it cannot be ignored)
}
}The difference is that names.add("Ada") can also be used as a statement on its own line, but 42; cannot.
Why This Design Helps
Target typing keeps lambdas short. You rarely write types, because the interface already lists them. It also keeps lambdas safe, because the compiler checks every lambda against a real method signature. The next chapter introduces the standard interfaces in java.util.function, which give you ready-made target types for common tasks. Later, the chapter on overloads shows what happens when one method name offers two possible target types.
Exercise
Given interface Doubler { int twice(int n); }, which of these lines compile? (1) Doubler d = n -> n * 2; (2) Doubler d = (String n) -> n + n; (3) var d = n -> n * 2; (4) Object d = (Doubler) n -> n * 2;
Show answer
Lines 1 and 4 compile. Line 1 gets its target type from the variable, and n is inferred as int. Line 2 fails because the explicit parameter type String does not match the method's int parameter. Line 3 fails because var gives the lambda no target type. Line 4 compiles because the cast supplies Doubler as the target type before the result is stored in an Object variable.
Exercise
Why does (a, b) -> a + b print 5 when assigned to an interface whose method is int combine(int a, int b) but prints 23 when assigned to one whose method is String combine(String a, String b) and called with "2" and "3"?
Show answer
The lambda takes its parameter types from the target interface's method. With int parameters, + adds numbers, so 2 + 3 is 5. With String parameters, + joins text, so "2" + "3" is "23". The same lambda text compiles to different code for each target type.
Exercise
Runnable r = () -> list.add("x"); compiles even though add returns boolean and run returns void. Why does Runnable r = () -> true; fail?
Show answer
An expression body for a void method must be something that could stand alone as a statement, such as a method call, and its result is ignored. A method call like list.add("x") qualifies. A plain value like true is not a valid statement, so it cannot be treated as void, and the compiler reports a bad return type.