×

java · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.