Card 01/ 09
Lambdas: Passing Behaviour to a Method as an Argument
The sort is already written; the one thing it needs from you is which of two invoices comes first.
A lambda is a short piece of behaviour written where it is used and passed to a method as an argument, such as (a, b) -> Long.compare(a.pence(), b.pence()). It is an object implementing an interface, and the method it is passed to decides which interface.
Take a list of invoices to sort by amount. The sorting code is written and correct; the one thing it does not know is which of two invoices comes first, and that has to get from you into it. Java's answer used to be an anonymous class (a class declared and instantiated in one expression, with no name): 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. The interface is decided by what the receiving method expects, which is why the same few tokens can mean different things in different calls. Here sort expects a Comparator, so the lambda becomes one.
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.
← → move through sections and cards