The second higher-order function you saw in action is sort. Unlike the other functions in this recipe, sort in Dart is a mutable function, which is to say, it alters the original data. Pure functions are supposed to simply return new data, so this one is an exception.
A sort function follows this signature:
int sortPredicate<T>(T elementA, T elementB);
The function will get two elements in the collection and it is expected to return an integer to help Dart figure out the correct order:
-1 | Less Than |
0 | Same |
1 |
Greater Than |
In our example, we delegated to the string's compareTo function, which will return the correct integer. All this can be accomplished with a single line:
names.sort((a, b) => a.last.compareTo(b.last));