Sorting a list of objects for a data table

i am trying to build out a datatable that will sort based upon fields.

my object is

data class Meal(
    val calories: Int,
    val salad: String,
    val mainCourse: String,
    val desert: String,
)

backing list for the table would be

val mealList = listOf<Meal>(
    Meal(calories = 10, salad = "Caesar Salad", mainCourse = "Salmon", desert = "pudding"),
    Meal(calories = 20, salad = "Garden Salad", mainCourse = "Eggs", desert = "ice cream"),
    Meal(calories = 30, salad = "Tuna Salad", mainCourse = "Chicken", desert = "pie"),
    Meal(calories = 40, salad = "Potato Salad", mainCourse = "Hot Dogs", desert = "cake"),
    Meal(calories = 40, salad = "Cobb Salad", mainCourse = "Steak", desert = "jello"),
)

was going to use somthing like this to hold the sorted data for the table

data class DataTableData<T>(
    var items:List<T>,
    var fieldList:MutableList<KProperty1<T, *>> = mutableListOf(),

    ){
    fun handleSortRequest( incoming : KProperty1<T, *>){
        fieldList.add(incoming)
        items = items.sortedWith(compareBy(fieldList))
    }
}

i can’t figure out how to sort the items based upon fieldList

Mutability design issues aside the problem here is that you can only sort by comparable class properties. To solve it you could declare your container like this:

data class DataTableData<T : Any>(
	var items: List<T>,
	var fieldList: MutableList<KProperty1<T, Comparable<*>>> = mutableListOf(),
) : Iterable<T> {
	override fun iterator() = items.iterator()
	
	fun handleSortRequest(incoming: KProperty1<T, Comparable<*>>) {
		fieldList.add(incoming)
		items = items.sortedWith(compareBy(*fieldList.toTypedArray()))
	}
}

and then you can use it as intended:

fun main() {
	val dataTable = DataTableData(mealList)
	dataTable.handleSortRequest(Meal::calories)
	dataTable.handleSortRequest(Meal::salad)
	dataTable.forEach(::println)
}
1 Like

ty for the help, i implemented this but it stops working after the fieldlist gets larger than 2, your example works great but if i plug in a third handlesortreqest it stops sorting.

** edit!!!

adding a reverse on the fieldlist made it behave as wanted.

fun handleSortRequest(incoming: KProperty1<T, Comparable<*>>) {
    fieldList.add(incoming)
    fieldList.reverse()
    items = items.sortedWith(compareBy(*fieldList.toTypedArray()))
}

Could you maybe provide a full example which doesn’t work for you? I tried my code with more properties and I hadn’t noticed anything wrong.