Comparable MIXIN class and
implements a compareTo method can be sorted.
The DateTime class and
TimeSpan class
are examples of built-in Rexx classes that can be sorted.
Any user-created class may also implement a compareTo
method to enable sorting.
For example, consider the following simple class:
::class Employee inherit Comparable
::attribute id
::attribute name
::method init
expose id name
use arg id, name
::method compareTo
expose id
use arg other
return id~compareTo(other~id) -- comparison performed using employee id
::method string
expose name
return "Employee" name
sort method needs to compare two Employee instances, it will call the
compareTo method on one of the instances, passing the second instance as an argument.
The compareTo method tells the sort method
which of the two instances should be first.
a = .array~new
a[1] = .Employee~new(654321, "Fred")
a[2] = .Employee~new(123456, "George")
a[3] = .Employee~new(333333, "William")
a~sort
do employee over a
say employee -- sorted order is "George", "William", "Fred"
end