Card 01/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
Passing Behaviour to a Method as an Argument
You want a list sorted by amount. The sorting code is written and correct, and the one thing it does not know is which of two invoices comes first. That one thing has to get from you into it.
Java's answer used to be an anonymous class: eight lines of scaffolding around one expression.
invoices.sort(new Comparator<Invoice>() {
@Override
public int compare(Invoice a, Invoice b) {
return Long.compare(a.pence(), b.pence());
}
});A lambda is the same thing with everything the compiler can work out left off. The type, the method name and the return all go, because there is only one method it could be implementing.
invoices.sort((a, b) -> Long.compare(a.pence(), b.pence()));It is not a new kind of value. A lambda is an object implementing an interface, and the interface is decided by what the method it is passed to expects — which is why the same three tokens mean different things in different calls.
So the useful question about any lambda is not what it does but what interface it landed in. Answer that and its parameter types, its return type and every restriction on it follow.