How would you assert an array (or a list) is sorte...
# announcements
l
How would you assert an array (or a list) is sorted by a given selector/property its elements have? My use case is enforcing the order of an enum based on one of its properties (its only property actually). EDIT: found a solution:
Copy code
enum ThatEnum(val thatProperty: Float) {
    FirstEntry(thatProperty = 10),
    AnotherEntry(thatProperty = 20),
    LastEntry(thatProperty = Float.POSITIVE_INFINITY);

    companion object {
        init {
            check(values().contentEquals(values().apply { sortBy { it.thatProperty } }))
        }
    }
}
That requires to
companion object
to be accessed for the check to execute, which is fine in my case since I use it to get instances of the enum early.
a
Are you talking about checking that in a test or in source code?
l
In source code so it stays contextual
p
It probably doesn’t matter but you could save some GC/memory by using
fold
instead. (Check that the property monotonically increases.)
l
That's a good idea @pedro!
đź‘Ť 1
m
Your requirement is being able to check at runtime that these constants and future additions will remain sorted according to a property, right?
l
Here's what I ended up using, with
fold
.