Sub topic 3
Writing Your First Lambda Expressions
In the last chapter you saw that a functional interface has exactly one abstract method. A lambda expression is a short way to write that one method without creating a whole class. You write the inputs, an arrow, and the work to do.
The Shape of a Lambda
Every lambda has three parts:
- Parameters are the inputs, written in parentheses.
- The arrow
->separates the inputs from the work. - The body is the code that runs. It can be one expression or a block of statements.
A Worked Example
Here is a small functional interface called Calculator. Its one method takes two numbers and returns a number.
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b; // expression body
Calculator multiply = (int a, int b) -> { // explicit types, block body
return a * b;
};
System.out.println(add.apply(2, 3)); // 5
System.out.println(multiply.apply(2, 3)); // 6
}
}Save this as CalculatorDemo.java, then run javac CalculatorDemo.java and java CalculatorDemo. You will see 5 and 6.
The lambda (a, b) -> a + b takes the place of the whole apply method. Calling add.apply(2, 3) runs the lambda's body with a set to 2 and b set to 3.
Expression Bodies and Block Bodies
An expression body is a single expression with no braces. Java returns its value for you, so you do not write return.
A block body is code inside curly braces { }. It can hold many statements. If the method returns a value, you must write return yourself.
| Body type | Example | Needs `return`? |
|---|---|---|
| Expression | `(a, b) -> a + b` | No |
| Block | `(a, b) -> { return a + b; }` | Yes, if a value is returned |
Use an expression body when the work fits on one line. Use a block body when you need several steps.
Inferred and Explicit Parameter Types
In (a, b) -> a + b there are no types. The compiler infers them, which means it works them out by itself. It knows Calculator.apply takes two int values, so a and b must be int.
You may also write the types out, as in (int a, int b) -> .... These are explicit types. If you write a type for one parameter, you must write types for all of them.
Different Numbers of Parameters
The parentheses change a little with the number of inputs:
- No parameters: use empty parentheses, as in
() -> System.out.println("Hi"). - One parameter: you can drop the parentheses, as in
name -> "Hello, " + name. - Two or more: parentheses are required, as in
(a, b) -> a - b.
@FunctionalInterface
interface Greeter {
String greet(String name);
}
public class GreeterDemo {
public static void main(String[] args) {
Runnable sayHi = () -> System.out.println("Hi");
Greeter greeter = name -> "Hello, " + name;
sayHi.run(); // Hi
System.out.println(greeter.greet("Ada")); // Hello, Ada
}
}Runnable is a functional interface built into Java. Its one method, run, takes no inputs and returns nothing.
Common Mistakes
- Writing
returnin an expression body, such as(a, b) -> return a + b;. This does not compile. Either removereturnor add braces. - Forgetting
returnin a block body that must give back a value. - Mixing typed and untyped parameters, such as
(int a, b) -> a + b.
Exercise
Rewrite the lambda (int a, int b) -> { return a - b; } as a Calculator lambda with inferred types and an expression body.
Show answer
(a, b) -> a - b
Exercise
Why does Calculator c = (a, b) -> { a * b; }; fail to compile?
Show answer
It uses a block body, so the result must be returned with return. A correct version is (a, b) -> { return a * b; } or the expression body (a, b) -> a * b.