Hello everyone! We are working on adding the `isSo...
# stdlib
d
Hello everyone! We are working on adding the
isSorted
family of extensions to the Kotlin standard library (see KT-78499). The family includes
isSorted
,
isSortedDescending
,
isSortedBy
,
isSortedByDescending
, and
isSortedWith
. Extensions for all array types will be provided, of course. We are currently deciding which other receiver types should have these extensions. For
List
the use cases are straightforward: validating preconditions before binary search, assertions in tests, and verifying expected ordering. However, for
Iterable
and
Sequence
the decision is less obvious. On one hand,
Sequence
already has the full
sorted
family, so adding
isSorted
would feel consistent. On the other hand, sequences and general iterables do not guarantee repeatable iteration, so checking
isSorted
and then relying on that result could be misleading if the underlying data changes. We would appreciate hearing about your practical scenarios where you would need
isSorted
on
Iterable
or
Sequence
. Your feedback would help us choose the right set of receiver types for this API. Feel free to reply here or leave a comment on the YouTrack issue.
y
FWIW,
List
doesn't guarantee repeatable iteration either. TOCTOU can easily happen here. Hence, I don't think
Iterable
vs
List
is actually an important distinction here, since both of them can have wildly different elements on different iterations. Similarly,
Sequence
fits the same bill here. I think all you need to do is mention in the docs that it's a terminal operator, and leave it at that. If someone needs
isSorted
for "before binary search" and similar use cases, then they need to copy the list, or to tell their users to not pass in a list that has a data race. Similarly, they'll just tell their users not to pass in an
Iterable
that produces different elements in different iterations
thank you color 1
➕ 1
d
We sometimes want to check that a sequence of values is non-decreasing. For example, the timestamps of events should never go backwards in time. However, instead of a terminal operation on the entire sequence, a more appropriate operation would be something that checks the current value against the previous value. Perhaps something like
checkInvariant { prev, current -> prev <= current}
. Similar reasoning would also apply to iterables, flows, or channels. Using
isSorted
seems a bit too narrow for these types of scenarios so a more general function for checking the current value against the previous might be more natural.
thank you color 1
e
5 cents, I always sort instead of checking (also doesn't happen often)
thank you color 1
➕ 1