I am trying to understand how does this works. ```...
# getting-started
s
I am trying to understand how does this works.
Copy code
list.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 :)
e
sortedWith(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
Copy code
list.sortedBy {
    when(it.state) {
        A -> -1
        B -> 0
        C -> 1
    }
}
s
I am passing multiple selectors to
compareBy
, how can I use
a
and
b
when doing it in this to implement some complex logic?
e
you can just implement
Comparator { a, b -> ... }
but what are you trying to do, it should not be common to need that
c
Note that if your states are an
enum class
, it's already done for you:
list.sortedBy { it.state }
will sort them in the same order as they are declared in code.