https://kotlinlang.org logo
#announcements
Title
# announcements
l

louiscad

07/01/2020, 8:15 AM
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

Ashish Kumar Joy

07/01/2020, 8:23 AM
Are you talking about checking that in a test or in source code?
l

louiscad

07/01/2020, 8:24 AM
In source code so it stays contextual
p

pedro

07/01/2020, 8:24 AM
It probably doesn’t matter but you could save some GC/memory by using
fold
instead. (Check that the property monotonically increases.)
l

louiscad

07/01/2020, 8:24 AM
That's a good idea @pedro!
👍 1
m

Matteo Mirk

07/01/2020, 8:32 AM
Your requirement is being able to check at runtime that these constants and future additions will remain sorted according to a property, right?
l

louiscad

07/01/2020, 8:34 AM
Here's what I ended up using, with
fold
.
7 Views