A collection is sorted only to take its first or last element
What it finds
items.sorted().first() sorts the whole collection, in O(n log n) time and with a copy, to find the smallest element, which min() finds in one pass. The same holds for sortedBy { } with minBy { }, and for the last element with max.
From the rule's source, sort_for_extreme.rs.
fun extremes(items: List<Int>, people: List<String>) { val low = items.sorted().first()tx0 reports: sorted() sorts everything to take one element with first() val longest = people.sortedBy { it.length }.lastOrNull()tx0 reports: sortedBy() sorts everything val firstTwo = items.sorted().take(2) val small = items.minOrNull()} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/kotlin:sort-to-take-one" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/kotlin:sort-to-take-one] reason="..."tx0 explain tx0/kotlin:sort-to-take-one shows the same in the terminal. Found a false positive? Report it.