Array.sort


#1

Wouldn't it better if Array.sort (and Array.fill) returned the array rather than Unit? This way we could chain calls like this: myArray.sort().forEach{...}


#2

Good point, but we should call this function sortInPlace() to emphasize that it mutates the array.


#3

Right.

We could then have Array.sort() make a copy, sort it and return the copy.

For lists we would have:
List.sort()   (returns a copy)
List.sortInPlace()  (not available)

MutableList.sort()  (returns a copy)
MutableList.sortInPlace()   (returns itself)


#4

I suggest to add methods to stdlib like sorted(), reversed(), etc. as I added them to stiters. This is how this was done in Smalltalk earlier: the ed-ending in sorted/reversed indicates to the user that a new collection is returned and the original one has remained unchanged.

Would be nice to have non-destructive collection methods in stdlib so that you can program somewhat in a functional style. IMHO there should be no sort/reverse methods except the ones inherited through the JDK. In Smalltalk there is no sort method as there is class SortedCollection. People are often surprised that using SortedCollection instead of sort sometimes results in much better performance. Reason is that the SortedCollection doesn’t need to be re-sorted to be sure that it is sorted and when items are only added sporadically to the SortedCollection performance of sorting is distributed over time and not done all at once.

/Oliver


#5

Just in case anyone else finds their way to this thread and is wondering, Oliver’s ‘-ed’ suggestion was implemented.

See for example sorted et al: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html.