Kotlin sortedBy syntax and examples

As a quick note, here’s an example of the Kotlin sortedBy syntax. Given this list of strings:

val names = listOf("kim", "julia", "jim", "hala")

the comments after these examples show how the Kotlin sortedBy function works:

names.sortedBy { it }          //[hala, jim, julia, kim]
names.sortedBy { it.length }   //[kim, jim, hala, julia]

As shown, the algorithms in between the curly braces determine how the collection (list, array, etc.) should be sorted.

It’s important to note that sortedBy doesn’t sort the names array; instead, it returns a new array that’s sorted, so you’ll want to use it like this:

val sortedNames = names.sortedBy { it }

As a final note, the algorithms in between the curly braces are known as anonymous functions or lambdas, and in Kotlin the variable name it lets you refer to the elements in the array/list. That is, when you write it.length, you’re asking for the length of each element in the list as those elements are passed into the anonymous function.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.