suhas
09/24/2021, 2:35 AMlist.sortedWith(compareBy ({
when(it.state) {
A -> -1
B -> 0
C -> 1
}
}))
This returns a list were all the elements with state A come first, followed by B and then followed by C. I am just not able to wrap head around this though. I understand how comparable works by overriding compareTo function and comparing two objects that the function gets. But not this. Can someone please explain this to me :)ephemient
09/24/2021, 2:51 AMsortedWith(comparator)
uses comparator.compare(a, b)
instead of a.compareTo(b)
as sorted()
would use
compareBy(f).compare(a, b)
returns f(a).compareTo(f(b))
you don't need sortedWith(compareBy())
, there's a standard function
list.sortedBy {
when(it.state) {
A -> -1
B -> 0
C -> 1
}
}
suhas
09/24/2021, 2:55 AMcompareBy
, how can I use a
and b
when doing it in this to implement some complex logic?ephemient
09/24/2021, 2:58 AMComparator { a, b -> ... }
but what are you trying to do, it should not be common to need thatCLOVIS
09/24/2021, 7:30 PMenum class
, it's already done for you: list.sortedBy { it.state }
will sort them in the same order as they are declared in code.