https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

suhas

09/24/2021, 2:35 AM
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

ephemient

09/24/2021, 2:51 AM
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

suhas

09/24/2021, 2:55 AM
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

ephemient

09/24/2021, 2:58 AM
you can just implement
Comparator { a, b -> ... }
but what are you trying to do, it should not be common to need that
c

CLOVIS

09/24/2021, 7:30 PM
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.