Now i want to write a sort function which accepts the property by which i want the list to be sorted by as an parameter.
Let's hope that by "the property", you can settle for something like a function reference:
data class Person(val name: String, val age: Int)
var people = listOf(Person("Jane Doe", 25), Person("John Smith", 24), Person("Jen Jones", 37))
fun <R: Comparable<R>> sort(selector: (Person) -> R) {
people = people.sortedBy(selector)
}
fun main() {
println(people)
sort(Person::name)
println(people)
}
I could also use sort(Person::age) if I wanted to sort by age.
If your pseudocode is more literal, and you want a String parameter for the property name, you should start by asking yourself "why?". But, if you feel that you have a legitimate reason to use a String, one approach would be:
data class Person(val name: String, val age: Int)
var people = listOf(Person("Jane Doe", 25), Person("John Smith", 24), Person("Jen Jones", 37))
fun sort(property: String) {
people = when(property) {
"name" -> people.sortedBy(Person::name)
"age" -> people.sortedBy(Person::age)
else -> throw IllegalArgumentException("and this is why you should not be doing this")
}
}
fun main() {
println(people)
sort("name")
println(people)
}