'what is the difference between sortBy - sortedBy and sortWith - sortedWith in kotlin

I'm just exploring kotlin collection and I observed one important behavior.


val sports = listOf<Sports>(
        Sports("cricket", "7"),
        Sports("gilli", "10"),
        Sports("lagori", "8"),
        Sports("goli", "6"),
        Sports("dabba", "4")
    )

    sports.sortedBy { it.rating } // sortedByDescending is to sort in descending
        .forEach({ println("${it.name} ${it.rating}") })


}

class Sports(name: String, rating: String) {
    var name: String = name
    var rating: String = rating
}

above I can only get sortedBy method i.e which starts with sorted. I don't know why I'm not getting sortBy and sortWith operations.

can anyone give explanation for this in simple words.



Solution 1:[1]

sortBy (Just sort the elements inside the list) -> Used on MutableList

 /**
     * Sorts elements in the list in-place according to natural sort order of the value returned by specified [selector] function.
     * 
     * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
     */
    public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit {
        if (size > 1) sortWith(compareBy(selector))
    }

sortedBy (Returns a new list with its elements sorted) -> Used on List

/**
 * Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector] function.
 * 
 * The sort is _stable_. It means that equal elements preserve their order relative to each other after sorting.
 */
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
    return sortedWith(compareBy(selector))
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gastón Saillén