This actually has nothing to do with Kotlin. It's related to the Java API's Comparator interface, and how Collections.sort uses it.
从the documentation:
Compares its two arguments for order. Returns a negative integer,
zero, or a positive integer as the first argument is less than, equal
to, or greater than the second.
Now let's try this out for the arguments you gave:
- 1 - 5 = -4 (a negative integer), so 1 is less than 5.
- 5-2=3(正整数),所以5大于2.
- etc...
Collections.sort
doesn't know anything about what y - x means. It simply respects the defined contract of the Comparator interface that any implementor also needs to respect (if it wants to work).
It just so happens that y - x
is an implementation that does respect that contract, because Math.