Decorate-sort-undecorate idiom: Difference between revisions

Line 596:
 
=={{header|Kotlin}}==
Kotlin already has a `sortedBy` function that can sort using a key extractor directly, so there is no need to decorate/undecorate. Nevertheless, the code example below shows how to decorate, sort and undecorate.
 
<syntaxhighlight lang="kotlin">
fun main() {
val list = listOf("Rosetta", "Code", "is", "a", "programming", "chrestomathy", "site")
println(sorted(list, .sortedBySchwartzian(String::length))
}
 
/**
fun <T, C: Comparable<C>> sorted(list: Collection<T>, keyFn: (T) -> C): List<T> =
* Returns a sorted list using the Schwartzian Transform which guarantees minimal use of the
list
* key extractor function. Use when the key extractor function is an expensive operation.
.map { it to keyFn(it) }
*/
fun <T, CR: Comparable<CR>> sorted(list: Collection<T>, .sortedBySchwartzian(keyFn: (T) -> CR): List<T> =
this.map { it to keyFn(it) }
.sortedBy { it.second }
.map { it.first }
49

edits