java · level 3 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every lambda needs an interface to fit into.
A lambda is not a type by itself. It fits wherever Java expects an interface with exactly one method left without a body: a . The lambda becomes the body of that method. That is how removeIf knew what your lambda meant.
You can make your own. interface Discount { double apply(double price); } describes any rule that turns one price into another. Now price -> price * 0.9 and price -> price - 5 are both a Discount, and you can store them, pass them and call apply on them.
Put above it. If anyone later adds a second bodyless method, the compiler stops them before every lambda breaks.
import java.util.List;
public class Main {
@FunctionalInterface
interface Discount {
double apply(double price);
}
static double checkout(double price, Discount discount) {
return discount.apply(price);
}
public static void main(String[] args) {
Discount sale = price -> price * 0.9;
Discount voucher = price -> price - 5;
Discount none = price -> price;
for (Discount discount : List.of(sale, voucher, none)) {
System.out.println(checkout(40.0, discount));
}
}
} checkout never knows which rule it got. It calls apply, and the lambda does the rest.
guess first
One lambda calls another. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
@FunctionalInterface
interface Greeter {
String greet(String name);
}
public static void main(String[] args) {
Greeter polite = name -> "Good morning, " + name + ".";
Greeter shout = name -> polite.greet(name).toUpperCase();
System.out.println(shout.greet("Ada"));
}
}
your turn
Your turn. Write a password rule.
On line 14, write a lambda that allows passwords of 8 characters or more.
output
press run to see what happens
fix it
Someone added a method. Now nothing compiles. Can you fix it?
output
press run to see what happens
- Java says the
@FunctionalInterfacelabel is unexpected. Count the methods without a body. - A lambda can fill in only one bodyless method, and
Discountnow has two. - Delete line 5,
String label();, then run.
nailed it
your lambdas have a type of their own. :D
- A functional interface has exactly one method without a body.
- Any matching lambda can stand in for that interface.
@FunctionalInterfacemakes the compiler guard the one-method rule.
new words in your collection
- functional interface
- @FunctionalInterface
This lesson isn’t saved. A free account remembers every lesson you finish.