Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Kotlin sortBy() seems to operate in reverse order?

When I perform:

val array = arrayListOf<String?>(null, "hello", null)
array.sortBy { it == null }
println(array)

I expect it would print null values first as that's the selector I specified. However, println(array) returns [hello, null, null].

Why is this?

like image 676
Zorgan Avatar asked Sep 19 '25 21:09

Zorgan


1 Answers

The expression:

it == null

returns a Boolean result true or false and this is what you use to sort the array.
The value true is greater than false, you can see it by executing:

println(false < true)

which will print

true

With your code:

array.sortBy { it == null }

for every item that the expression it == null returns false it will be placed before any item for which it will return true.
So do the opposite:

array.sortBy { it != null }

Result:

[null, null, hello]
like image 50
forpas Avatar answered Sep 22 '25 10:09

forpas