Card 02/ 09
All 9 cards
ExampleDifficulty: Intermediate1 min
Sorting With a Comparator Written on One Line
One call, one lambda, and the pieces the compiler filled in without being told.
invoices.sort((a, b) -> Long.compare(a.pence(), b.pence()));| Written | Inferred |
|---|---|
(a, b) | Both are Invoice, from List<Invoice>.sort(Comparator<? super Invoice>) |
-> | That this is the body of compare, the only abstract method on Comparator |
Long.compare(...) | That the int it produces is the return value |
Nothing was left out that the compiler could not supply. sort declares its parameter as a Comparator, Comparator has exactly one abstract method, and that method takes two Invoice values and returns an int.
What to notice: the lambda has no type written anywhere. Its type came from the place it was passed to, which is why an identical lambda handed to a different method would be a different interface entirely.